【发布时间】:2020-10-05 10:19:07
【问题描述】:
当屏幕关闭时,我在发出 HTTP 请求时遇到了很多麻烦。我目前正在通过以下方式使用 HttpUrlConnection:
class HttpPostRequest extends AsyncTask<String, Void, String> {
private String httpResponse = null;
public String getResponse() {
return httpResponse;
}
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setDoOutput(true);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.write(params[1]);
writer.flush();
writer.close();
connection.connect();
Log.e("Response", connection.getResponseCode() + "");
Log.e("Url", connection.getRequestMethod());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
connection.disconnect();
// print result
return response.toString();
}
} catch (Exception e) {
Log.e(e.toString(), "Something with request");
return "";
}
return "";
}
}
但是,虽然当我正在编程的应用程序在屏幕上时它可以正常工作,但当屏幕关闭时它无法正常工作。很高兴听到社区的建议。谢谢!
【问题讨论】:
-
它是如何工作的?你有例外吗?
标签: android android-studio http httpurlconnection