2012-09-29 2 views
0

저는 개발의 안드로이드 측면에 초보자이며, 내가 시험해보고 싶었던 한 가지는 HTTP Get을 사용하는 방법이었습니다. 텍스트가 보내지고 결과가 문자열로 돌아 오도록 전체 메서드 설정이 있습니다. 그러나 내가 알고 싶은 것은 문자열을 가져 와서 실제로 필요한 부분 만 추출하는 방법이었습니다. 예를 들어 문자열이 다시Android HTTP 가져 오기 및 결과 문자열

{"id":"124343","name":"somename" } 

에 와서 그냥 얻을 원한다면 그의 id 부분은 내가 안드로이드에 그렇게 얼마나 시작합니다. 나는 문서를 검색하고 있지만, 지금까지는 아무 것도 발견하지 못했으며, JSON을 사용하여 발견 한 대부분의 것들도 돌아 보았다.

아래 코드는 현재 내가 사용하고있는 코드입니다 (여러 다른 게시물에서 함께 컴파일했습니다).하지만 JSON을 구문 분석 용으로 전환해야 할 필요가 있으며 그 위치를 변경할 위치가 확실하지 않습니다.

 //This class is called after a button is pressed and the HTTPGet string is compiled from text within a textview and a static string (this already works) 
    private class LongRunningGetIO extends AsyncTask<Void, Void, String> { 
    protected String getASCIIContentFromEntity(HttpEntity entity) 
      throws IllegalStateException, IOException { 
     InputStream in = entity.getContent(); 
     StringBuffer out = new StringBuffer(); 
     int n = 1; 
     while (n > 0) { 
      byte[] b = new byte[4096]; 
      n = in.read(b); 
      if (n > 0) 
       out.append(new String(b, 0, n)); 
     } 
     return out.toString(); 
    } 

    @Override 
    protected String doInBackground(Void... params) { 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpContext localContext = new BasicHttpContext(); 
     String question = questionText.getText().toString(); 
     String newString = httpPath + "?userText=" + question; 
     Log.i("Message", newString); 
     HttpGet httpGet = new HttpGet(newString); 
     String text = null; 
     try { 
      HttpResponse response = httpClient.execute(httpGet, 
        localContext); 
      HttpEntity entity = response.getEntity(); 
      text = getASCIIContentFromEntity(entity); 


     } catch (Exception e) { 
      return e.getLocalizedMessage(); 
     } 
     return text; 
    } 


    protected void onPostExecute(String results) { 
     if (results != null) { 
      Log.i("String", results); 
     } 
    } 
} 

답변

2

이 JSON 문자열

JSONObject obj = new JSONObject(YourJSONString); 
String id = obj.getString("id"); 
String name = obj.getString("name"); 
+0

T 행크스 팁, 지금은 JSON을 사용하지 않는거야 그래서 JSON 없이이 일을하는 또 다른 방법은 내가 구문 분석을 위해 JSON을 사용하여 전환해야합니까? 게시물을 내 코드 –

+0

으로 업데이트 할 것입니다.이 방법은 이미 수행 한 결과 문자열을 JSON 개체로 바꾸기 때문에 이미 형식화되어 있으므로 필요한 항목을 추출 할 수있었습니다. 도움을 주셔서 감사합니다 –

+0

당신은 절대적으로 환영합니다. 다행스럽게 도울 수있어! –

1

에서 데이터를 추출하는 방법은 당신이 원하는 ::이인가

HttpGet httpGet = new HttpGet(newString); 
String text = null; 
    try { 
      HttpResponse response = httpClient.execute(httpGet, localContext); 
      InputStream content = response.getEntity().getContent(); 
      BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); 

      while ((text = buffer.readLine()) != null) { 

       //Work with "text" here... 
      //Split the string as you wish with "text.split();" function.. 

      } 
     } catch (Exception e) { 
      return e.getLocalizedMessage(); 
     }