【发布时间】:2017-02-05 12:07:57
【问题描述】:
我正在尝试使用 HttpUrlConnection 进行 POST 调用,但没有成功。 我经常收到“IllegalStateException:已连接”错误消息。 我对重用连接不感兴趣。请检查我的代码并告诉我是否做错了什么:
public static final int CONNECTION_TIME_OUT = 10000;
public SimpleResponse callPost(String urlTo, Map<String, String> params) {
System.setProperty("http.keepAlive", "false");
HttpURLConnection conn = null;
SimpleResponse response = new SimpleResponse(0, null);
try {
URL url = new URL(urlTo);
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(CONNECTION_TIME_OUT);
conn.setReadTimeout(CONNECTION_TIME_OUT);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "close");
conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(paramsToString(params));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = conn.getInputStream();
String result = StringUtils.fromInputStream(in);
response = new SimpleResponse(responseCode, result);
in.close();
} else {
response = new SimpleResponse(responseCode, null);
}
} catch (Exception e) {
e.printStackTrace();
}
if (conn != null) {
conn.disconnect();
}
return response;
}
private String paramsToString(Map<String, String> params) {
if (params == null || params.isEmpty()) {
return "";
}
Uri.Builder builder = new Uri.Builder();
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.appendQueryParameter(entry.getKey(), entry.getValue());
}
return builder.build().getEncodedQuery();
}
更新:
有时有效,有时无效!
适用于某些项目,但不适用于其他项目!
完全相同的代码,每次都出现相同的异常:已连接
为什么我每次都无法获得新的连接?
【问题讨论】:
-
当然,activity有问题,请添加您的代码。
-
@W4R10CK 我只是在 AsyncTask 中进行调用
-
@HamzehSoboh 哪条线路已经连接好?
-
顺便说一句,conn.disconnect() 块确实应该在 finally 块中完成。这可能是您收到错误的原因,因为可能有一些其他异常会处理已连接的消息,然后所有后续消息都会失败。
-
这一行之后
conn = (HttpURLConnection) url.openConnection();直接conn.connected的值为true,任何像setUseCaches或setDoOutput这样的操作都会通过异常。
标签: android post httpurlconnection