Android HttpUrlConnection在getResponseCode()上挂起

时间:2015-12-02 17:00:26

标签: android android-studio httpurlconnection

所以,从我的(android)api我试图通过在登录页面上发布用户名和密码来登录我的Web服务。然后,服务器应该重定向到成功URL或错误URL,具体取决于身份验证是否成功。

代码如下:

String urlParameters = "_username=" + URLEncoder.encode(username, "UTF-8")
                            + "&_password=" + URLEncoder.encode(password, "UTF-8");

URL url = new URL(MainActivity.I_SAIL_URL + "/member/login_check");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("api", "requestKey");

connection.setConnectTimeout(5000);
//connection.setReadTimeout(5000);
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");

//Send request
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
os.close();

int responseCode = connection.getResponseCode();

// if there is a response code AND that response code is 200 OK, do
// stuff in the first if block
if (responseCode == HttpURLConnection.HTTP_OK) {
    //do stuff
}
else {
    //do other stuff
}

现在,在Android 6.0模拟器中一切正常,但它不适用于在4.1.2上运行的实际设备。当我取消注释connection.setReadTimeout()时,它会抛出超时异常,如果不这样做,它会运行大约10到15分钟,然后有时会给我预期的结果。

仅在服务器重定向时才会出现此问题。如果没有重定向,一切都很好。我尝试了HttpUrlConnection.setFollowRedirects(true)以及connection.setInstanceFollowRedirects(true),但没有成功。

任何可能导致这种行为的想法?

0 个答案:

没有答案