2016-02-19 328 views
0

我有連接到我的服務器的問題。以下代碼返回-1作爲響應代碼,並返回null作爲響應消息。HttpUrlConnection返回-1狀態碼

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; 
} 

雖然debbuging url和正文內容(這是在代碼中加載)是正確的。當我嘗試使用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")沒有幫助。

+0

將代碼添加到您確定響應代碼和結算消息以及返回頁面的位置。顯示'load'類型。也許你應該顯示'加載'內容。 – greenapps

+0

我編輯過的第一篇文章。謝謝 – laik

+0

請把所有的代碼放在一個代碼塊中。您沒有顯示讀取返回頁面的代碼。 – greenapps

回答

0

我解決了這個問題。正是在這一行:

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

當我把它改爲:

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

它開始工作。