android HttpURLConnection无法断开连接?
目标使用android HttpURLConnection无法断开连接?,android,connection,Android,Connection,目标使用HttpURLConnection内部AsyncTask当我取消AsyncTask并请求中止或取消连接时,AsyncTask停止正常,但HttpURLConnection仍在发送请求并从服务器返回值 如何使HttpURLConnection完全停止取消所有请求或中止请求 这是我使用的代码 public static String post_string(String url, String urlParameters) throws IOException {
HttpURLConnection
内部AsyncTask
当我取消AsyncTask
并请求中止或取消连接时,AsyncTask
停止正常,但HttpURLConnection
仍在发送请求并从服务器返回值
如何使HttpURLConnection
完全停止取消所有请求或中止请求
这是我使用的代码
public static String post_string(String url, String urlParameters) throws IOException
{
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
} catch (MalformedURLException e) {
Log.e(Logger, "MalformedURLException While Creating URL Connection - " + e.getMessage());
throw e;
} catch (IOException e) {
Log.e(Logger, "IOException While Creating URL Connection - " + e.getMessage());
throw e;
}
conn.setDoOutput(true);
conn.addRequestProperty("User-Agent", "Mozilla/5.0");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//if has Post inputs
conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.length()));
OutputStream os = null;
System.setProperty("http.keepAlive", "false");
try {
os = conn.getOutputStream();
} catch (IOException e) {
Log.e(Logger, "IOException While Creating URL OutputStream - " + e.getMessage());
throw e;
}
try {
os.write(urlParameters.toString().getBytes());
} catch (IOException e) {
Log.e(Logger, "IOException While writting URL OutputStream - " + e.getMessage());
throw e;
}
InputStream in = null;
try {
in = conn.getInputStream();
} catch (IOException e) {
Log.e(Logger, "IOException While Creating URL InputStream - " + e.getMessage());
throw e;
}
String output = null;
try {
output = slurp(in);
} catch (IOException e) {
Log.e(Logger, "IOException While Reading URL OutputStream - " + e.getMessage());
throw e;
} finally {
try {
os.close();
in.close();
} catch (IOException e) {
Log.e(Logger, "IOException While Closing URL Output and Input Stream - " + e.getMessage());
}
}
conn.disconnect();
Log.i("Server output " , output);
return output;
}
private static String slurp(InputStream in) throws IOException
{
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
这就是我用来中止连接的方法
conn.disconnect();
有没有关于如何中止的建议?当您停止
AsyncTask
时,如mTask.cancel(true)代码>只需调用连接断开()代码>我做了,但控制室仍在工作!它从服务器返回值并将信息发布到服务器,这真是奇怪。您调试了它吗?断开连接后,未打开任何套接字,并确保服务器未返回任何数据,请发布所有相关代码是的,我已对其进行了调试,并且在断开连接后,LogCat打印服务器返回信息!发生这种情况是因为aim使用了slurp(InputStream in)
?您有最终{os.close();in.close();}
,在连接之前关闭它。断开连接()在我取消AsyncTask
并关闭os.close()时仍然存在同样的问题;in.close()代码>LogCat仍在打印服务器响应!