【问题标题】:HttpUrlConnection sometimes gives EOF exceptionHttpUrlConnection 有时会给出 EOF 异常
【发布时间】:2015-11-10 13:12:53
【问题描述】:

我正在使用HttpUrlConnection 并使用 POST 方法从 Web 服务器获取一些数据。有时,我会收到回复,有时会收到EOFexception 这些是我已经尝试过的解决方案:

1)  System.setProperty("http.keepAlive", "false");
2) if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
                    connection.setRequestProperty("Connection", "close");
                }

下面是我来自AsyncTask 类的代码; 代码:

@Override
    protected JSONObject doInBackground(KeyValuePair... keyValuePairs) {

        JSONObject jsonResponse = new JSONObject();
        HttpURLConnection connection = null;
        // check if is Internet is available before making a network call
        if (isInternetAvailable()) {
            try {
                jsonResponse = new JSONObject();
                URL url = new URL(urlStr);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setUseCaches(false);
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestProperty("charset", "UTF-8");
                if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
                    connection.setRequestProperty("Connection", "close");
                }
                // setting post params
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < keyValuePairs.length; i++) {
                    builder.append(URLEncoder.encode(keyValuePairs[i].getKey(), "UTF-8") + "=" + URLEncoder.encode(keyValuePairs[i].getValue(), "UTF-8") + "&");
                    GeneralUtils.print("key : " + keyValuePairs[i].getKey() + ", value : " + keyValuePairs[i].getValue());
                }
                String postData = builder.toString();
                postData = postData.substring(0, postData.length() - 1);
                GeneralUtils.print("postData " + postData);
                byte[] postDataByteArr = postData.getBytes();
                connection.setFixedLengthStreamingMode(postDataByteArr.length);
                connection.setConnectTimeout(20000);
                DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
                dataOutputStream.writeBytes(postData);
                dataOutputStream.flush();
                dataOutputStream.close();
                GeneralUtils.print("respCode " + connection.getResponseCode());
                // if connection was not successful
                if (connection.getResponseCode() != 200) {
                    jsonResponse.put("status", "Failure");
                    jsonResponse.put("message", "Something went wrong. Please Try Again");

                } else {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line = null;
                    StringBuilder sb = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    reader.close();
                    String response = sb.toString();
                    GeneralUtils.print("NetworkCall Server response " + response);
                    jsonResponse = new JSONObject(response);

                }
            } catch (JSONException e) {
                GeneralUtils.print("NetworkCall.JSONEx 162 " + e);
            } catch (MalformedURLException e) {
                GeneralUtils.print("NetworkCall.MalformedURLEx " + e);
            }  catch (IOException e) {
                try {
                    jsonResponse.put("status", "No Internet Connection");
                    jsonResponse.put("message", "Please check your Internet connection and try again");
                } catch (JSONException e1) {
                    GeneralUtils.print("NetworkCall.JSONEx " + e);
                }
            } finally {
                connection.disconnect();
            }
        } else {
            // if Internet is not available
            try {
                jsonResponse.put("status", "No Internet Connection");
                jsonResponse.put("message", "Please check your Internet connection and try again");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return jsonResponse;
    }

提前非常感谢!

【问题讨论】:

    标签: java android android-asynctask httpurlconnection


    【解决方案1】:

    截至目前,我正在关注here 发布的解决方法,该解决方法基本上要求尝试连接 N 次以绕过 EOF 异常问题。 就我而言,当我捕获 EOFException 时,我会根据 reconnectCount 再次调用 doInBackground;

     CODE :
    
    catch (IOException e) {
                    try {
                        if (reConnectCount <= 10) {
                            reConnectCount++;
                            jsonResponse = doInBackground(keyValuePairs);
                        } else {
                            jsonResponse.put("status", "No Internet Connection");
                            jsonResponse.put("message", "Please check your Internet connection and try again");
                        }
                    } catch (JSONException e1) {
                        GeneralUtils.print("NetworkCall.JSONEx " + e);
                    }
                }
    

    jsonResponse 本质上以 JSON 形式保存服务器响应。因此,每当doInBackground 成功执行(即没有被捕获并返回jsonResponse)时,我们都会覆盖调用doInBackground 的jsonResponse 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 2013-03-07
      • 1970-01-01
      • 2012-05-17
      • 2012-12-27
      • 2019-09-25
      • 1970-01-01
      相关资源
      最近更新 更多