set方法不适用于HttpsURLConnection

时间:2011-09-23 12:44:38

标签: java android web-services rest

我正在尝试在java中发出一个休息请求。我在Firefox中使用RestClient测试了Web服务,效果很好。

当我尝试在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;

}

我在这一点上陷入困​​境,找不到任何可以使这项工作的事情。

谢谢!

1 个答案:

答案 0 :(得分:0)

我实际上认为这是HttpsURLConnection的一个错误。当我将其更改为HttpURLConnection对象时,一切正常。