如何在Android应用中发送HTTP请求以访问REST API

18

有人能解决我的问题吗?我想在Android中发送HTTP请求以访问REST API(PHP)。

谢谢。


see the related section. - Harry Joy
1
可能是重复的问题:如何在Android中进行HTTP请求 - Vaibhav Mule
2个回答

15

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

Log.i(tag, result); 这行代码的意思是什么? - sandy
1
Log.i会向你的计算机发送“信息消息”,以便你能轻松地查看结果。 - Joe Simpson
如果我必须使用HTTPS,我在上面需要做哪些更改?还是它可以正常工作吗? - uniruddh
嗨,我不理解这一行代码:new HttpGet(URL + q)...我们实例化了一个新的 HttpGET 对象...但是“q”是什么? - learner

2

基本上取决于您的需求,但假设是一个简单的带有JSON正文的POST请求,它会看起来像这样(我建议使用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();
}

最后,我鼓励你在任何类型的后台线程(executor、thread、asynctask等)中运行此代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接