如何在Android应用程序发送HTTP请求来访问REST API [英] How send http request in android app to access REST API

查看:131
本文介绍了如何在Android应用程序发送HTTP请求来访问REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何一个可以解决我的问题。我想在Android中发送一个HTTP请求访问 REST API(PHP)。

Can any one solve my problem. I want to send a http request in android to access 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()  
} 

这篇关于如何在Android应用程序发送HTTP请求来访问REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆