1
我想在java中作出休息请求。我使用Firefox中的RestClient测试了Web服务,它效果很好。设置方法不工作HttpsURLConnection
当我尝试修改java中的HttpsUrlConnection实例的值不会改变,我得到一个500响应代码。
这里是我的代码:
public String getAuthToken() throws IOException {
URL url =new URL("https://webserviceurl"); // webservice url is the url of the webservice
String data = URLEncoder.encode("username") + "=" + URLEncoder.encode("myusername","UTF-8");
data+= "&" + URLEncoder.encode("password") + "=" + URLEncoder.encode("pass","UTF-8");
HttpsURLConnection conn =(HttpsURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setHostnameVerifier(new AllowAllHostnameVerifier()); //this works HostName verifier changes
conn.setRequestMethod("POST"); // this doens't work. requestMethod is still set to GET
conn.setDoOutput(true); // this doesnt work. DoOutput still set on false
conn.setRequestProperty("Content-Type", "application/json"); // doens't work either
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
wr.write(data);
wr.flush();
wr.close();
//conn has a 500 response code
if (conn.getResponseCode()==200)
{
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(isr);
String token = rd.readLine();
rd.close();
return token;
}
else
return null;
}
我在这一点上stucked并不能发现什么,使这项工作。
谢谢!
你确定需要'POST'用户名和密码,而不是使用'GET',并将它们作为参数在url中吗? – ernazm
这是一个内部服务器错误。此错误只能通过修复Web服务器软件来解决。 **这不是客户端问题**。 Web服务器站点的运营商应该定位和分析日志,以提供有关错误的更多信息。 – mrkhrts
好的,但实际的方法没有为HttpsURLConnection做任何事情。我已经将其更改为HttpURLConnection并且它可以工作。 –