2013-11-15 3 views
0

Android에서 새로 생겼지 만 Android에서 XML 파서를 사용하여 내 앱에서 RSS를 구문 분석했습니다. 이제 서버에서 /로 새 응용 프로그램 데이터를 보내고 받겠습니다.Android에서 XML 또는 JSON을 반환하는 URL에서 데이터를 가져 오는 방법

필자는 웹 API의 서버 측을 개발하여 테스트했으며 지금까지 작동 중입니다. 따라서이 URL을 호출하면

http://URL/api/getQuery/value1/value2 

이 XML (및 필요한 경우 JSON)이 표시됩니다.

<ArrayOfstring> 
    <string>4.5</string> 
    <string>Glu Mobile</string> 
    <string>4.2.0</string> 
    <string>1392/07/18</string> 
    <string>500</string> 
    <string>112MB</string> 
    <string>free</string> 
    <string>creator</string> 
    <string>describtion</string> 
    <string>similarapp</string> 
</ArrayOfstring> 

이제 url을 호출하고 XML 또는 JSON 문자열을받은 다음 배열 또는 목록으로 구문 분석하려고합니다. 어떻게해야합니까?

답변

1

사용법 volley 라이브러리 ... 매우 유용 할 것입니다. 링크가 있습니다. 다운로드하고 검토하십시오. 처음부터 매우 쉽게 할 수 있습니다. .

https://github.com/ogrebgr/android_volley_examples

또는

당신은 서버에서 JSON 데이터를 얻을 수 AsyncTask를를 사용할 수 있습니다.

import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.provider.Settings.System; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import android.view.View.OnClickListener; 

public class AsyncTaskActivity extends Activity implements OnClickListener { 

Button btn; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    btn = (Button) findViewById(R.id.button1); 
    // because we implement OnClickListener we only have to pass "this" 
    // (much easier) 
    btn.setOnClickListener(this); 
} 

public void onClick(View view) { 
    // detect the view that was "clicked" 
    switch (view.getId()) { 
    case R.id.button1: 
     new LongOperation().execute(""); 
     break; 
    } 
} 

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

    @Override 
    protected String doInBackground(String... params) { 
     String url = params[0]; 

     HttpClient httpClient = new DefaultHttpClient(); 
     HttpGet request = new HttpGet(url);   
     request.setHeader("Content-Type", "text/xml"); 
     HttpResponse response; 
     try { 
      response = httpClient.execute(request); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return response; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     // Result is in String Format 
     // you can use JSON api to convert into JSONObject 

    } 

    @Override 
    protected void onPreExecute() {} 

    @Override 
    protected void onProgressUpdate(Void... values) {} 
} 

}

관련 문제