我使用POST API调用使用以下函数发布一些数据:
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(40000);
conn.setReadTimeout(40000);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setDefaultUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Cache-Control", "max-age=0");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty(JsonKeys.DATE_KEY, getTimeStamp());
if (params != null) {
// Write serialized JSON data to output stream.
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(params.toString());
wr.close();
}
int status = conn.getResponseCode();
StringBuilder sb = new StringBuilder();
try {
if (status == HttpURLConnection.HTTP_OK || status == HTTP_CREATED) {
InputStream is = conn.getInputStream();
int ch;
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
is.close();
return new JSONObject(sb.toString());
} else {
throw new IOException("We encountered some problem with the request. Please try again later");
} catch (JSONException jex) {
MessageUtils.showLog(jex);
} finally {
if (conn != null) {
MessageUtils.showLog("connection disconnected");
conn.disconnect();
}
}
此POST请求需要等待至少40秒才能从服务器响应。这段代码在大多数设备上运行得非常好,但在某些设备上,请求在10秒后突然结束。我得到502响应(比如10秒后)。服务器日志没有发送响应的跟踪(由我的后端开发人员确认)。我在前端收到的502错误流包含:
<HEAD><TITLE>Server Hangup</TITLE></HEAD>
我不知道为什么这对于不同的移动设备或不同的Android API表现不同。有人可以帮助我洞察这个问题或解决方案吗?我一直坚持这个问题几个小时,无法找到解释/解决方案。
这是我们在apache访问日志中收到的堆栈跟踪:
[Wed May 01 13:54:54.142877 2019] [proxy:error] [pid 23000:tid 140687508961231] (111)Connection refused: AH00957: HTTP: attempt to connect to 127.0.0.1:9000 (localhost) failed
[Wed May 01 13:54:54.142995 2019] [proxy:error] [pid 23000:tid 140687508961231] AH00959: ap_proxy_connect_backend disabling worker for (localhost) for 60s
[Wed May 01 13:54:54.143001 2019] [proxy_http:error] [pid 23000:tid 140687508961231] [client 160.32.32.202:256560] AH01114: HTTP: failed to make connection to backend: localhost
我们服务器中的代理配置是这样的:
<Location "/v2/">
ProxyPass http://0.0.0.0:9000/ retry=0 timeout=500
ProxyPassReverse http://0.0.0.0:9000
</Location>
ProxyPreserveHost On
ProxyRequests Off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
502实际上是'坏网关'。这绝对是一个服务器问题。你有一些apache模块检查稳定连接,该模块检测到你的连接不正常。
从更新的问题可以看出,您的代理上的“重试”属性为0.以下是文档中的含义:
https://httpd.apache.org/docs/2.4/mod/mod_proxy.html#proxypass
重试
连接池工作程序以秒为单位重试超时。如果到后端服务器的连接池工作程序处于错误状态,则Apache httpd将不会将任何请求转发到该服务器,直到超时到期为止。这样可以关闭后端服务器以进行维护,并在以后将其重新联机。值为0表示始终在没有超时的情况下重试处于错误状态的工作程序。
所以肯定问题是在不同的请求而不是在不同的android。请检查您的要求。您发送的请求可能不同,服务器可以检测到连接已死,让您认为问题出在android中。您还可以使用重试参数并将其设置为默认重试= 60。