簡體   English   中英

如何在Android應用程序中發送http請求以訪問REST API

[英]How send http request in android app to access REST API

任何人都可以解決我的問題。 我想在android中發送一個http請求來訪問REST API(PHP)..

謝謝

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()  
} 

它基本上取決於你需要什么,但假設一個簡單的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();
}

最后,我建議您在任何類型的后台線程(執行程序,線程,異步任務等)中運行此代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM