2015-11-10 3 views
3

Я использую HttpUrlConnection и используя метод POST для получения некоторых данных с веб-сервера. Иногда я получаю ответ, а иногда я получаю EOFexception Эти решения я уже пробовал:HttpUrlConnection иногда дает исключение EOF

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; 
    } 

Много много спасибо заранее!

ответ

0

На данный момент я следую обходному решению here , которое по существу диктует попытку подключения N количества раз, чтобы обойти проблему исключения EOF. В моем случае, когда я поймаю EOFException, я снова вызываю doInBackground в зависимости от rennectCount;

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), мы перезаписываем объект jsonResponse вызывающего doInBackground.

Смежные вопросы