Android 网络编程(二)HttpClient

来源:互联网 发布:怎么在mac上新建文件夹 编辑:程序博客网 时间:2024/06/03 21:39

上一篇说了HTTP协议,这篇主要说一下HTTP请求所要使用的类,HttpClient。


HttpClient简介

HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

HttpClient 提供的主要的功能如下:

  1. 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
  2. 支持自动转向
  3. 支持 HTTPS 协议
  4. 支持代理服务器等

HttpClient 请求

使用 HttpClient 需要以下 6 个步骤:
1. 创建 HttpClient 的实例
2. 创建某种连接方法的实例,在这里是GetMethod。在 GetMethod 的构造函数中传入待连接的地址
3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
4. 读 response
5. 释放连接。无论执行方法是否成功,都必须释放连接
6. 对得到后的内容进行处理

Get请求

class HttpClientGetThread extends Thread{    @Override    public void run() {        HttpResponse response;        InputStream in = null;        // 默认的HttpClient实例        HttpClient httpClient = new DefaultHttpClient();        // 创建HttpGet实例        HttpGet get = new HttpGet("http://www.baidu.com");        try {            //连接到服务器            response = httpClient.execute(get);            if(response.getStatusLine().getStatusCode()==200){                HttpEntity entity = response.getEntity();                Header contentType = entity.getContentType();                if(contentType != null)                Log.i(TAG, "name="+contentType.getName()+",value="+contentType.getValue());                long length = entity.getContentLength();                Log.i(TAG, "length="+length);                //获取输入流                in = entity.getContent();            }        } catch (Exception e) {            e.printStackTrace();        }        final String content = readStreamToString(in);        mTvResponse.post(new Runnable() {            @Override            public void run() {                //更新ui                mTvResponse.setText(content);            }        });    }}

readStreamToString用来从输入流中读取数据。

private String readStreamToString(InputStream is){    if(is == null)return null;    BufferedReader reader = new BufferedReader(            new InputStreamReader(is));    String content = "";    String line = "";    try {        //从输入流读取数据,readLine方法会阻塞,直到有数据返回,或者连接断开。        while ((line = reader.readLine()) != null) {            content += line;        }    } catch (IOException e) {        e.printStackTrace();    }    return content;}

效果图如下:
这里写图片描述

Post请求

class HttpClientPostThread extends Thread{    @Override    public void run() {        HttpResponse response;        InputStream in = null;        // 默认的HttpClient实例        HttpClient httpClient = new DefaultHttpClient();        // 创建HttpPost实例        HttpPost post = new HttpPost("http://120.25.226.186:32812/login");        try {            List<NameValuePair> params = new ArrayList<NameValuePair>();            //设置参数            params.add(new BasicNameValuePair("username", "520it"));            params.add(new BasicNameValuePair("pwd", "520it"));            post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));            //连接到服务器            response = httpClient.execute(post);            if(response.getStatusLine().getStatusCode()==200){                HttpEntity entity = response.getEntity();                Header contentType = entity.getContentType();                if(contentType != null)                    Log.i(TAG, "name="+contentType.getName()+",value="+contentType.getValue());                //获取输入流                in = entity.getContent();            }        } catch (Exception e) {            e.printStackTrace();        }        final String content = readStreamToString(in);        Log.i(TAG, "post content:"+content);    }}

打印结果如下:

07-30 17:23:53.867: I/MainActivity(5329): name=Content-Type,value=application/json;charset=UTF-807-30 17:23:53.868: I/MainActivity(5329): post content:{"success":"登录成功"}

欢迎大家关注、评论、点赞
你们的支持是我坚持的动力。

阅读全文
0 0
原创粉丝点击