HttpUrlConnection返回-1状态代码

时间:2016-02-19 15:56:27

标签: java android httpurlconnection

我连接到服务器时遇到问题。以下代码返回-1作为响应代码,返回null作为响应消息。

  protected Boolean doInBackground(MyTaskParams... params) {
    URL url = null;
    String load = params[0].jobj.toString();
    try {
        url = new URL(params[0].serverUrl);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setConnectTimeout(3000);
        urlConnection.setReadTimeout(3000);
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        urlConnection.setChunkedStreamingMode(0);
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();

        OutputStreamWriter osw = new OutputStreamWriter(urlConnection.getOutputStream());
        osw.write(load);
        osw.flush();
        osw.close();

        if(urlConnection.getResponseCode()==200 && urlConnection.getResponseMessage().contains("true") ) return true;
        else return false;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

虽然debreging url和body内容(代码加载)是正确的。当我尝试使用这些与Fiddler的参数连接服务器时,它工作得很好,我获得了200个状态代码。你有什么想法吗?

我传递jData对象作为jobj:

        JSONObject User=new JSONObject();
        JSONObject Mobile=new JSONObject();
        JSONObject jData=new JSONObject();
        try {
            User.put ("UserLogin", "test");
            User.put ("UserPassword", "test");
            Mobile.put ("MobileIDD", IDD);
            Mobile.put("MobileToken", token);
            jData.put("Mobile", Mobile);
            jData.put("User", User);
        } catch (JSONException e) {
            e.printStackTrace();
        }

@EDIT System.setProperty("http.keepAlive", "false")的解决方案没有帮助。

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。就在这一行:

if(urlConnection.getResponseCode()==200 && urlConnection.getResponseMessage().contains("true") ) return true;

当我将其更改为:

int code = urlConnection.getResponseCode();
if (code==200.....)

它开始工作了。