2013-09-23 1 views
0

임 BufferedReader의 불완전 응답, 간단한 HTTP 얻을 내 결과에 내가 볼안드로이드 무엇 임 잘못

불완전한 응답, 일을하고 HttpGet?

class GetDocuments extends AsyncTask<URL, Void, Void> { 

    @Override 
    protected Void doInBackground(URL... urls) { 

     Log.d("mensa", "bajando"); 

      //place proper url 
      connect(urls); 

      return null; 
    } 

    public static void connect(URL[] urls) 
    { 

     HttpClient httpclient = new DefaultHttpClient(); 

     // Prepare a request object 
     HttpGet httpget = new HttpGet("http://tiks.document.dev.chocolatecoded.com.au/documents/api/get?type=tree"); 

     // Execute the request 
     HttpResponse response; 
     try { 

      response = httpclient.execute(httpget); 



      // Examine the response status 
      Log.d("mensa",response.getStatusLine().toString()); 

      // Get hold of the response entity 
      HttpEntity entity = response.getEntity(); 
      // If the response does not enclose an entity, there is no need 
      // to worry about connection release 

      if (entity != null) { 

       // A Simple JSON Response Read 
       InputStream instream = entity.getContent(); 
       String result= convertStreamToString(instream); 
       // now you have the string representation of the HTML request 

       Log.d("mensa", "estratagema :: "+result); 

       JSONObject jObject = new JSONObject(result); 

       Log.d("mensa", "resposta jObject::"+jObject); 

       Log.d("mensa", "alive 1"); 

       JSONArray contacts = null; 
       contacts = jObject.getJSONArray("success"); 

       Log.d("mensa", "resposta jObject::"+contacts); 

       Log.d("mensa", "alive"); 

       //instream.close(); 

      } 


     } catch (Exception e) {} 
    } 



     private static String convertStreamToString(InputStream is) { 
     /* 
     * To convert the InputStream to String we use the BufferedReader.readLine() 
     * method. We iterate until the BufferedReader return null which means 
     * there's no more data to read. Each line will appended to a StringBuilder 
     * and returned as String. 
     */ 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
       Log.d("mensa", "linea ::"+line); 

      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 
} 

내가 그것을 전화 : 내가 잘립니다 응답으로 불완전한를 참조

GetDocuments get = new GetDocuments(); 

     URL url = null; 
    try { 
     url = new URL("ftp://mirror.csclub.uwaterloo.ca/index.html"); 
    } catch (MalformedURLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 


    //URL url = new URL("http://www.google.es"); 

    get.execute(url); 

편집 한 여기에 코드

? 문자열이 잘립니다 방법

이 때문에 로그 크기? 하지만 다른 문제이며, 응답의 이미지 아래는 구문 분석하지 않는다는 것입니다에주의하시기 바랍니다?

enter image description here

감사합니다!

+0

INCOMPLETE 응답으로 더 자세히 지정할 수 있습니까? 나는 당신의 코드를 디버깅하려하고 JSONException이 던져진다. 09-23 14 : 04 : 42.045 : E/a (507) : org.json.JSONException : java.lang.Boolean 유형의 성공시 값이 JSONArray로 변환 될 수 없음 – edisonthk

+0

예외가 발생하지 않으며 다음으로 수정을 참조하십시오. 응답, tnx에 대한 잘린 문자열을 확인하십시오. – MaKo

+0

오, 나중에 코드를 편집하기 때문에 예외가 발생합니다. 귀하의 GetDocuments 클래스 연결 메서드에서 귀하의 예외에 로그를 추가하면 그것을 볼 수 – edisonthk

답변

1

나는 일의 마지막 몇 정확히 같은 문제를 했어 . 내 코드가 Wi-Fi를 통해 작동하지만 3G가 아닌 것으로 나타났습니다. 다시 말해서 나는 일반적인 스레딩 후보자를 모두 제거했습니다. 또한 디버거에서 코드를 실행하고 client.execute (...)가 실행 된 후 10 초 동안 기다렸을 때도 발견되었습니다.

내 생각 엔

response = httpclient.execute(httpget); 

자체에서 비동기 호출 있다는 것이다 그것은 천천히 되돌아에게 부분적인 결과를 때 ... 따라서 JSON의 직렬화는 잘못.

대신 나는 콜백 실행이 버전의 ...

try { 
    BasicResponseHandler responseHandler = new BasicResponseHandler(); 
    String json = httpclient.execute(httpget, responseHandler);   
} finally { 
    httpclient.close(); 
} 

갑자기 모든 일을 시도했다. 문자열을 원하지 않거나 자신 만의 코드를 원한다면 ResponseHandler 인터페이스를 살펴보십시오. 희망이 도움이됩니다.

2

나는이 문제를 해결할 것입니다 알고하지 않습니다하지만 당신은 당신의 방법을 제거 할 수 간단하게 사용

String responseString = EntityUtils.toString(response.getEntity()); 
1

자바 문자열의 크기 제한 때문에 확인했습니다. 나는이 문자열을 "abcd"에 ressponse를 추가하여 점검했고 logcat에 응답 문자열을 출력했다. 그러나 문자열 "abcd"가 추가되지 않은 채 잘릴 수 있습니다.

try { 
BasicResponseHandler responseHandler = new BasicResponseHandler(); 
String json = httpclient.execute(httpget, responseHandler); 
json= json+"abcd"; 
Log.d("Json ResponseString", json); 
} finally { 
httpclient.close(); 
} 

입니다

그래서 나는 응답을 수집하는 arrayString을 넣어. 배열을 만들려면, 내가 사용하여 내 JSON 형식의 응답 "}"이 코드는 아래와 같습니다

BasicResponseHandler responseHandler = new BasicResponseHandler(); 
    String[] array=client.execute(request, responseHandler).split("}"); 

그런 다음 당신은 JSON 개체에 대한 각 개체를 구문 분석 할 수 있습니다 (이 작업 주위 아니라)을 갈라 json 배열을 사용자 정의 클래스와 함께 사용하십시오.

응답을 저장하는 다른 좋은 방법을 얻는다면 pls는 모든 다른 json 응답에 대해 사용자 지정 메서드를 만들기 때문에 공유합니다.).

지금 내가 응답을 처리 할 수 ​​GSON 라이브러리를 사용하고 당신

아르 샤드

1

내가 '직접 인해 명성 코멘트 캔트하지만 https://stackoverflow.com/a/23247290/4830567에 대한 응답으로 내가 자바 문자열의 크기 제한 2GB의 (정수에 관한 것을 지적한다 느꼈다. MAX_VALUE) 여기에 잘라내 기가 발생하지 않았습니다.

https://groups.google.com/d/msg/android-developers/g4YkmrFST6A/z8K3vSdgwEkJ에 따르면 크기 제한이있는 logcat입니다. 따라서 "abcd"를 추가하고 logcat에서 인쇄가 작동하지 않습니다. String 자체는 추가 된 문자를가집니다. 이전에 링크 된 논의에서도 HTTP 프로토콜 자체의 크기 제한이 종종 요인 일 수 있지만 대부분의 서버와 클라이언트는이 제약 조건을 내부적으로 처리하여 사용자에게 노출시키지 않는다고 언급했습니다.