2013-12-14 2 views
1

Я выполняю запрос на сервер Apache с DefaultHttpClient. Я пытаюсь получить ответ. Когда ответ подобен 100 символам, работает нормально, byt, когда у меня есть более сильный отклик, как 300 символов. У меня есть выход сокета: сокет закрывается.android SocketException: Socket closed

исключения:

12-14 11:23:26.905: W/System.err(10082): java.net.SocketException: Socket closed 
12-14 11:23:26.905: W/System.err(10082): at org.apache.harmony.luni.platform.OSNetworkSystem.read(Native Method) 
12-14 11:23:26.905: W/System.err(10082): at dalvik.system.BlockGuard$WrappedNetworkSystem.read(BlockGuard.java:273) 
12-14 11:23:26.905: W/System.err(10082): at org.apache.harmony.luni.net.PlainSocketImpl.read(PlainSocketImpl.java:458) 
12-14 11:23:26.905: W/System.err(10082): at org.apache.harmony.luni.net.SocketInputStream.read(SocketInputStream.java:85) 
12-14 11:23:26.905: W/System.err(10082): at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103) 
12-14 11:23:26.905: W/System.err(10082): at org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:134) 
12-14 11:23:26.905: W/System.err(10082): at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:174) 
12-14 11:23:26.905: W/System.err(10082): at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:188) 
12-14 11:23:26.905: W/System.err(10082): at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:178) 
12-14 11:23:26.913: W/System.err(10082): at com.androidhive.pushnotifications.JSONParser.getJSONFromUrl(JSONParser.java:174) 
12-14 11:23:26.913: W/System.err(10082): at com.androidhive.pushnotifications.JSONParser.doInBackground(JSONParser.java:233) 
12-14 11:23:26.913: W/System.err(10082): at com.androidhive.pushnotifications.JSONParser.doInBackground(JSONParser.java:1) 
12-14 11:23:26.913: W/System.err(10082): at android.os.AsyncTask$2.call(AsyncTask.java:185) 
12-14 11:23:26.913: W/System.err(10082): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 
12-14 11:23:26.913: W/System.err(10082): at java.util.concurrent.FutureTask.run(FutureTask.java:138) 
12-14 11:23:26.921: W/System.err(10082): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 
12-14 11:23:26.921: W/System.err(10082): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 
12-14 11:23:26.921: W/System.err(10082): at java.lang.Thread.run(Thread.java:1019) 

Мой код:

DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 
     HttpResponse getResponse= null; 



     if(json_post!=null){ 
      StringEntity se=null; 
      try { 
       se = new StringEntity(json_post.toString()); 
      } catch (UnsupportedEncodingException e3) { 
       // TODO Auto-generated catch block 
       e3.printStackTrace(); 
      } 
      //sets the post request as the resulting string 
      httpPost.setEntity(se); 
     } 
     HttpProtocolParams.setUserAgent(httpClient.getParams(), "Mozilla/5.0");try { 
      getResponse = httpClient.execute(httpPost); 

     } catch (ClientProtocolException e2) { 
      statusCode = "ClientProtocolException"; 
      e2.printStackTrace(); 
     } catch (IOException e2) { 
      statusCode = "IOException"; 
      e2.printStackTrace(); 
     } finally { 
      httpClient.getConnectionManager().shutdown(); // Close the instance here 
     } 



     if (getResponse == null) return null; 
     statusCode = ""+getResponse.getStatusLine().getStatusCode(); 
     if (!statusCode.equals(""+HttpStatus.SC_OK)) { 
      Log.w(getClass().getSimpleName(), 
       "Error " + statusCode + " for URL " + url); 

      return null; 
     } 


     HttpEntity getResponseEntity = getResponse.getEntity(); 

     InputStream inputStream = null; 
     try { 
      inputStream = getResponseEntity.getContent(); 
     } catch (IllegalStateException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 

     ByteArrayOutputStream content = new ByteArrayOutputStream(); 

     // Read response into a buffered stream 
     int readBytes = 0; 
     byte[] sBuffer = new byte[512]; 
     try { 
      while ((readBytes = inputStream.read(sBuffer)) != -1) { 
       content.write(sBuffer, 0, readBytes); 
      } 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 

     // Return result from buffered stream 
     String dataAsString = new String(content.toByteArray()); 

пожалуйста, помогите :)

+0

Что такое линия 174? – EJP

+0

этот -> content.write (sBuffer, 0, readBytes); – user1309635

+0

Глупости. Строка 174 вызывает read(). Посмотрите на трассировку стека. content.write (...) даже не использует сокет. Зачем это бросать исключение «socket closed»? – EJP

ответ

0

Проблема: я был "выключение" conecction в конце концов witout этой линии работает отлично!

finally { 
    httpClient.getConnectionManager().shutdown(); // Close the instance 
} 
+0

Да, эта строка кода крайне преждевременна. Это должно было быть в конце метода. Мораль: не записывайте последовательные блоки «try»: пишите * вложенные * «try» блоки, если нужно. – EJP

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