HttpUrlConnection返回-1状态码
问题描述:
我有连接到我的服务器的问题。以下代码返回-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")
没有帮助。
答
我解决了这个问题。正是在这一行:
if(urlConnection.getResponseCode()==200 && urlConnection.getResponseMessage().contains("true")) return true;
当我把它改为:
int code = urlConnection.getResponseCode();
if (code==200.....)
它开始工作。
将代码添加到您确定响应代码和结算消息以及返回页面的位置。显示'load'类型。也许你应该显示'加载'内容。 – greenapps
我编辑过的第一篇文章。谢谢 – laik
请把所有的代码放在一个代码块中。您没有显示读取返回页面的代码。 – greenapps