【发布时间】:2022-02-02 10:32:03
【问题描述】:
我正在使用HttpURLConnection 向服务器发出请求并将一些数据保存在Database 中,但是当我发出请求时,它会执行两次,这会在数据库中添加两个相同的行。
注意:我也从 iOS 向服务器发出相同的请求,并且它运行良好,这只发生在 Android 上
这是我提出请求的代码:
URL url = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = (OutputStream)httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name" ,"UTF-8") + "=" + URLEncoder.encode(user,"UTF-8")+"&"
+URLEncoder.encode("user_id" ,"UTF-8") + "=" + user_id+"&"
+URLEncoder.encode("manager_id" ,"UTF-8") + "=" + manager+"&"
+URLEncoder.encode("company_id" ,"UTF-8") + "=" + company+"&"
+URLEncoder.encode("user_role" ,"UTF-8") + "=" + URLEncoder.encode(user_role ,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
final char[] buf = new char[256];
final StringBuffer sb = new StringBuffer();
while (true) {
int length = reader.read(buf);
if (length == -1) break;
sb.append(buf, 0, length);
}
reader.close();
inputStream.close();
【问题讨论】:
-
您正在关闭中间的输出流。你能测试同样的东西,但最后关闭它们(在你关闭输入流的同时)。最后还要调用 httpURLConnection.disconnect() 。 iOS 和 Android 使用不同的套接字机制。大概与这个事实有关。同样在调用阅读器之前,请对输出流进行刷新。另一点要检查的是服务器的响应速度有多快?不确定Android是否会在一段时间后发送自动重试,以防服务器没有响应。
-
@Besart 你用的是哪个版本的安卓?
-
确保代码不在 Android Lifecyle Hook 中。
-
我会放一些调试日志或附加调试器,看看这段代码是否从某个地方运行了两次,比如生命周期钩子。
-
@pringi 在这种情况下,关闭输出流是良性的。调用
disconnect()会禁用连接池。它可能没有任何帮助。
标签: java android xml httpconnection