HttpUrlConnection有时会给出EOF异常

时间:2015-11-10 13:12:53

标签: java android android-asynctask httpurlconnection

我正在使用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;
    }

许多人提前感谢!

1 个答案:

答案 0 :(得分:0)

截至目前,我正在遵循发布here 的解决方法,该解决方案基本上要求尝试连接N次以绕过EOF异常问题。 在我的情况下,当我捕获EOFException时,我再次调用doInBackground,具体取决于reconnectCount;

 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成功执行(即没有得到Caught并返回jsonResponse),我们就会覆盖调用doInBackground的jsonResponse对象。