Android学习——Apache HTTP Client

Apache HTTP Client

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包。
HttpClient下载地址。在Android中已经集成了HttpClient。

GET请求

http地址

String path="http://www.baidu.com";

HTTPGet连接对象

HttpGet get=new HttpGet(path);

取得HttpClient对象

HttpClient httpClient=new DefaultHttpClient();

向服务器发送请求,并返回相应对象

HttpResponse response=httpClient.execute(get);

获取响应的状态码,取得返回的字符串

int status=response.getStatusLine().getStatusCode();
switch (status){
    case HttpStatus.SC_OK:
        //200
        HttpEntity entity=response.getEntity();
        //取得返回的字符串
        String result=EntityUtils.toString(entity,"utf-8");
        System.out.println(result);
        break;
    case HttpStatus.SC_NOT_FOUND:
        //404
        break;
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        //500
        break;
}

在这里插入图片描述

POST请求

使用post方法进行参数传递时,需要使用NameValuePair来保存要传递的参数。另外,还需要设置所使用的字符集。
使用apache HttpClient的POST请求

private void postRequest(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            String path="http://apis.baidu.com/apistore/weatherservice/citylist";
            //创建请求对象
            HttpPost post=new HttpPost(path);
            //传递参数
            ArrayList<NameValuePair> params=new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("cityname","朝阳"));
            try {
                HttpEntity entity = new UrlEncodedFormEntity(params);
                post.setEntity(entity);
                HttpClient httpClient=new DefaultHttpClient();
                HttpResponse response=httpClient.execute(post);
                switch (response.getStatusLine().getStatusCode()){
                    case HttpStatus.SC_OK:
                        //200
                        String result=EntityUtils.toString(response.getEntity());
                        System.out.println(result);
                        break;
                    case HttpStatus.SC_NOT_FOUND:
                            //404
                            Log.i("HttpClient","404");
                            break;
                    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
                            //500
                            Log.i("HttpClient","500");
                            break;
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

在这里插入图片描述

小结

两种请求方式的区别:
get:大小不能超过4KB,速度快,会在URL上显示,不安全。
post:大小不限制,速度比get慢,不会在URL上显示,安全性高。

猜你喜欢

转载自blog.csdn.net/UUUUUltraman/article/details/89328549