2011-04-24 82 views
18

任何人都可以解決我的問題。我想在android系統發送一個HTTP請求訪問 REST API(PHP)..如何在android應用程序中發送http請求以訪問REST API

感謝

+0

的運行這段代碼見相關章節。 – 2011-04-24 08:37:44

+1

[使用android進行HTTP請求]的可能重複(http://stackoverflow.com/questions/3505930/make-an-http-request-with-android) – 2015-07-28 10:42:26

回答

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 2011-04-24 09:04:12

+1

Log.i正在向您的計算機發送「信息消息」,以便您輕鬆查看結果。 – 2011-04-24 12:20:36

+0

如果我必須使用HTTPS,我必須在上面做什麼更改?或者它會正常工作? – astuter 2014-05-21 08:40:36

2

這主要取決於你所需要的,但假設一個簡單的POST請求與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等)

相關問題