【发布时间】:2016-11-28 12:01:42
【问题描述】:
当服务器需要更长的时间来响应时(当它传递一个更大的JSONObject)时,我无法捕捉对服务器的 POST 请求的响应。
当我们调用响应时间较长的GET方法时,没有问题。当我们调用POST 并传递一个相对较小的JSONObject 时,该方法会注册一个响应。
正在通过new Task().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) 从AsyncTask 调用该方法。
当从 Postman 触发时,响应会在 155 秒后返回,但它会到达。另一方面,当从应用程序触发时,代码什么也不做,最终触发SocketTimeoutException。(无论出于何种原因,我们将超时(连接和读取超时)设置为 10 分钟)服务方法如下。我会很感激任何提示。
public static JSONObject requestWebService(String serviceUrl, JSONObject jsonObject) throws Exception {
private static final int CONNECTION_TIMEOUT = 1000 * 600;
private static final int DATARETREIVAL_TIMEOUT = 1000 * 600
HttpURLConnection urlConnection = null;
try {
URL urlToRequest;
String message;
urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
urlConnection.setReadTimeout(DATARETREIVAL_TIMEOUT);
if (jsonObject != null) {
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
message = jsonObject.toString();
OutputStream os = new BufferedOutputStream(urlConnection.getOutputStream());
os.write(message.getBytes());
os.flush();
os.close();
} else {
urlConnection.setRequestMethod("GET");
}
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new Exception("Acces unauthorized " + statusCode + ".");
} else if (statusCode != HttpURLConnection.HTTP_OK) {
throw new Exception("Server unavailable " + statusCode + ".");
}
return new JSONObject(ReplicationClient.convertInputStreamToString(urlConnection.getInputStream()));
} catch (MalformedURLException e) {
fileLogger.error(logHeader + e.getMessage(), e);
throw new Exception("Error " + e.getMessage(), e);
} catch (SocketTimeoutException e) {
fileLogger.error(logHeader + e.getMessage(), e);
throw new Exception("Error " + e.getMessage(), e);
} catch (IOException e) {
fileLogger.error(logHeader + e.getMessage(), e);
throw new Exception("Error " + e.getMessage(), e);
} catch (JSONException e) {
fileLogger.error(logHeader + e.getMessage(), e);
throw new Exception("Error " + e.getMessage(), e);
} catch (Exception e) {
fileLogger.error(logHeader + e.getMessage(), e);
throw new Exception("Error " + e.getMessage(), e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
【问题讨论】:
-
CONNECTION_TIMEOUT和DATARETREIVAL_TIMEOUT的值是多少?您知道这些方法以 毫秒 为单位获取值吗?我认为您已将值设置为 seconds ? -
对不起,这里是:private static final int CONNECTION_TIMEOUT = 1000 * 600;私有静态最终 int DATARETREIVAL_TIMEOUT = 1000 * 600;
-
刚刚注意到OutputStream对象没有关闭,可能是这个问题吗?
-
values 对我来说看起来不错,你知道抛出异常的时间有多长吗?
-
它只是挂在那里,然后只是抛出超时异常(10分钟后,我们设置的时间间隔)。 @rhari,我尝试关闭 OutputStream 对象,但没有任何区别..
标签: android android-asynctask httpurlconnection