【问题标题】:Multiple HTTP request happening with single call on frequent network change in android多次HTTP请求发生在android中频繁网络变化的单次调用
【发布时间】:2016-09-28 15:43:42
【问题描述】:

我正在为我在 android 中的 JSON 上传创建一个 HTTP URL 连接。该请求是一个意图服务。我有一个广播接收器,它检查网络变化并调用 Intent 服务进行上传。 但这样做时,当用户经常将 Wifi 网络更改为蜂窝网络或 Vic-verse 时,有时会多次上传相同的 JSON。

BroadcastReciver.java

public void onReceive(Context context, Intent intent) {

    if (ConnectivityManager.CONNECTIVITY_ACTION.equalsIgnoreCase(intent.getAction())) {
        if (Utils.hasActiveInternet(context)) {

            TripManager.uploadUnSubmittedTripsAsync(context, DataStore.getApplicationPath(context));

            Logger.log("OSBroadcastReceiver","onReceive",new String[]{"Network available"});

        }else
            Logger.log("OSBroadcastReceiver","onReceive",new String[]{"Network unavailable"});

    } 
}

上传.java

private ServiceResponse executeServiceRequestInternal() {
    ServiceResponse serviceResponse = null;
    HttpURLConnection connection = null;
    boolean delay = false;
    if (!Utils.hasActiveInternet(mContext)) {
        pushError("error");
    } else {

        try {
            if (jsonFile.exists()) {
                do {
                    connection = (HttpURLConnection) getServiceUrl(mRequest.serviceUrl).openConnection();
                    setHttpRequestType(mRequest, connection);
                    setContentType(mRequest, connection);
                    setHeaders(mRequest, connection);

                    connection.setUseCaches(false);
                    connection.setDoInput(true);
                    if (mRequest.requestType != GET_REQUEST) {
                        connection.setDoOutput(true);
                    }
                    connection.setConnectTimeout(mRequest.requestTimeout);
                    connection.setReadTimeout(mRequest.requestTimeout);
                    connection.setRequestProperty("Connection", "close");
                    connection.setRequestProperty("Keep-Alive", "off");
                    if (mRequest.requestData != null && mRequest.requestData.length() > 0) {
                        sendRequestWithData(connection);
                    }

                    connection.connect();

                    int responseCode = connection.getResponseCode();

                    if (delay) {
                        Thread.sleep(TIME_BEFORE_RETRY);
                    }
                    if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_ACCEPTED && responseCode != HttpURLConnection.HTTP_CREATED) {
                        String serverResponse = connection.getResponseMessage();
                        if (null == serverResponse) serverResponse = serverError;

                        serviceResponse = getServiceResponse(responseCode,
                                serverResponse);
                        pushServerError(responseCode, serverResponse);
                    } else {
                        InputStream is = connection.getInputStream();
                        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                        String line;
                        StringBuffer response = new StringBuffer();
                        while ((line = rd.readLine()) != null) {
                            response.append(line);
                            response.append('\r');
                        }
                        rd.close();

                        String resultString = response.toString();
                        is.close();
                        if (TextUtils.isEmpty(resultString)) {
                            serviceResponse = getServiceResponse(
                                    HttpURLConnection.HTTP_NO_CONTENT, "");
                            deleteTrip();
                        } else {
                            serviceResponse = getServiceResponse(
                                    HttpURLConnection.HTTP_OK, resultString);
                            deleteTrip();
                        }
                        break;
                    }
                    // we did not succeed with connection (or we would have returned the connection).
                    connection.disconnect();
                    // retry
                    mRetryCounter++;
                    delay = true;

                } while (mRetryCounter < MAX_RETRY_COUNT);


            } else {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

    }
    return serviceResponse;
}

提前致谢。

【问题讨论】:

  • 每次用户更改网络时,他都会从以前的网络断开连接并连接到新网络,并且您的服务会被调用两次。你检查这个吗?
  • 你的问题是?如果您只是想防止重复上传,只需在您的服务中添加一个计数器...
  • 我没有使用计数器,但由于它是一个意图服务,我正在检查 JSON 文件是否存在。但看起来内部有一些 URLConnection 池保存正在根据日志上传的数据
  • 尝试添加connection.setChunkedStreamingMode(0);
  • 即使那样也没有运气。

标签: java android json httpurlconnection


【解决方案1】:

我遇到了同样的问题,在添加 connection.setChunkedStreamingMode(0) 后它就解决了;这是你可以参考的sn-p,

HttpURLConnection request = (HttpURLConnection) url.openConnection();

            request.setUseCaches(false);
            request.setDoOutput(true);
            request.setDoInput(true);
            request.setConnectTimeout(CONNECTION_TIMEOUT);
            request.setRequestMethod(HTTP_POST);
            request.setReadTimeout(CONNECTION_TIMEOUT);
            request.setChunkedStreamingMode(0);

            DataOutputStream printout = new DataOutputStream(request.getOutputStream());
            NameValuePair dataToSend = new NameValuePair(AppEnvironment.DATA, data);
            // printout.write(getQuery(dataToSend));
            printout.writeBytes(getQuery(dataToSend));
            printout.flush();
            printout.close();




 private String getQuery(NameValuePair params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();


        result.append(URLEncoder.encode(params.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(params.getValue(), "UTF-8"));
//        }

        return result.toString();
    }

【讨论】:

  • 什么 request.setChunkedStreamingMode(0);做?你能解释一下它的功能吗?
猜你喜欢
  • 1970-01-01
  • 2018-12-04
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 2016-06-10
  • 2018-01-26
  • 1970-01-01
  • 2015-03-06
相关资源
最近更新 更多