如何在android应用程序中发送http请求来访问REST API?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (27)

求大神解决下我的问题。我想在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()  
} 
用户回答回答于

它基本上取决于你需要什么,但假设一个带有JSON主体的简单的POST请求,它会看起来像这样:

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等)中运行这些代码,

扫码关注云+社区