2011-04-24 5 views
18

누구든지 내 문제를 해결할 수 있습니까? 나는REST API에 액세스하기 위해 Android 앱에서 http 요청을 보내는 방법

감사

.. REST API를 (PHP)에 액세스 할 수 안드로이드에 HTTP 요청을 보낼 그것은 기본적으로 당신이 필요하지만, 단순히 요청을 POST 가정에 따라 달라집니다
+0

모든 종류의에서이 코드를 실행하는 것이 좋습니다 것은 관련 섹션을 참조하십시오. –

+1

가능한 [Android로 HTTP 요청 만들기] (http://stackoverflow.com/questions/3505930/make-an-http-request-with-android) –

답변

14

http://breaking-catch22.com/?p=12

public class AndroidApp extends Activity { 

    String URL = "http://the/url/here"; 
    String result = ""; 
    String deviceId = "xxxxx" ; 
    final String tag = "Your Logcat tag: "; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     final EditText txtSearch = (EditText)findViewById(R.id.txtSearch); 
     txtSearch.setOnClickListener(new EditText.OnClickListener(){ 
      public void onClick(View v){txtSearch.setText("");} 
     }); 

     final Button btnSearch = (Button)findViewById(R.id.btnSearch); 
     btnSearch.setOnClickListener(new Button.OnClickListener(){ 
      public void onClick(View v) { 
       String query = txtSearch.getText().toString(); 
       callWebService(query); 

      } 
     }); 

    } // end onCreate() 

    public void callWebService(String q){ 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpGet request = new HttpGet(URL + q); 
     request.addHeader("deviceId", deviceId); 
     ResponseHandler<string> handler = new BasicResponseHandler(); 
     try { 
      result = httpclient.execute(request, handler); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     httpclient.getConnectionManager().shutdown(); 
     Log.i(tag, result); 
    } // end callWebService() 
} 
+0

Log.i (tag, result); 이 줄의 의미는 무엇입니까? – sandy

+1

Log.i가 컴퓨터에 '정보 메시지'를 보내므로 쉽게 결과를 볼 수 있습니다. –

+0

HTTPS를 사용해야 할 경우 위에 변경해야 할 사항은 무엇입니까? 또는 그것은 잘 작동 할 것입니다 ??? – astuter

2

JSON 본문에서는 이와 같이 보일 것입니다 (Apache HTTP 라이브러리 사용을 제안합니다).

HttpPost mRequest = new HttpPost(<your url>);  

DefaultHttpClient client = new DefaultHttpClient(); 
//In case you need cookies, you can store them with PersistenCookieStorage 
client.setCookieStore(Application.cookieStore); 

try { 
    HttpResponse response = client.execute(mRequest); 

    InputStream source = response.getEntity().getContent(); 
    Reader reader = new InputStreamReader(source); 

    //GSON is one of the best alternatives for JSON parsing 
    Gson gson = new Gson(); 

    User user = gson.fromJson(reader, User.class); 

    //At this point you can do whatever you need with your parsed object. 

} catch (IOException e) { 
    mRequest.abort(); 
} 

마지막으로, 나는 백그라운드 스레드 (집행, 실, AsyncTask를, 등)

관련 문제