2014-10-08 2 views
-4

안녕하세요,이 코드를 스레드에서 사용하고 싶습니다. 어떻게 할 수 있습니까 ?? 이 코드는 안드로이드에서 RSS 피드를 읽는 데 사용됩니다.안드로이드에서 http 호출하는 법

public String getXmlFromUrl(String url) { 
    String xml = null; 

    try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     xml = EntityUtils.toString(httpEntity); 

    } 
    catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } 
    catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 
    // return XML 
    return xml; 
} 
+0

입니까? 어쩌면 AsyncTask라는 클래스가 이런 일을 할 수 있습니다. –

+0

http://developer.android.com/training/basics/network-ops/connecting.html이 필요합니다. – EpicPandaForce

답변

0

네트워크 작업에 AsyncTask를 사용하십시오.

private class YourTask extends AsyncTask<Void, Void, String> { 

    @Override 
    protected String doInBackground(Void... arg0) { 

     String xml = null; 

     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      xml = EntityUtils.toString(httpEntity); 

     } 
     catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } 
     catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 
     // return XML 
     return xml; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     // result is your xml. You can use it here. 
    } 

    @Override 
    protected void onPreExecute() {} 

    @Override 
    protected void onCancelled() {} 
} 

당신은 new YourTask().execute((Void)null);

행운이 스레드를 호출 할 수 있습니다 :이 예입니다.

0

클래스 필드는 핸들러를 정의한 다음 아래 예제와 같이 코드를 배치합니다.

Handler handler = new Handler(); 
... 

public void MyOnClick(View v){ 
    new Thread(new Runnable() {   
     @Override 
     public void run() { 
      handler.post(new Rubnable()){ 
       {your code} 
      } 
     } 
    }).start(); 
} 

가장 좋은 방법은 ... AsyncTask를를 사용하는 스레드에서

관련 문제