HttpClient使用详解

在实际开发中,常常用到开源项目 HttpClinet 。HttpClinet 用到一个基础的 jar 包,如 httpcore-4.1.2.jar、应用层的 jar 包、httpclient-4.1.2.jar 包、commons-logging-1.1.1.jar 包

使用 HTTP GET 方法下载网页(其中,增加判断网页字符编码)

public static string downHtml(String url) throws IOException {

    //创建一个客户端,类似于打开一个浏览器
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try{
        //创建一个 GET 方法,类似于在浏览器地址栏输入一个地址
        HttpGet httpget = new HttpGet(url);
        //类似于在浏览器地址栏中输入回车,获得网页内容
        HttpResponse response = httpclient.execute(httpget);

        //网页字符编码判断
        Pattern pattern = Pattern.compile("text/html;[\\s*charset=(.*)]");
        Header arr = response.getHeaders("Content-Type");
        String charset = "utf-8";
        if(arr!=null || arr.length!=0){
            String content = arr[0].getValue().toLowerCase();
            Matcher m = pattern.matcher(content);
            if(m.find()){
                charset = m.group(1);
            }
        }

        //查看返回的网页内容,类似于在浏览器查看网页源代码
        HttpEntity entity = response.getEntity();
        if(entity != null){
            InputStream instream = entity.getContent();
            InputStreamReader ir = new InputStreamReader(instream, charset);
            BufferedReader reader = new BufferedReader(ir);
            StringBuilder builder = new StringBuidler();
            char[] chars = new char[4096];
            int length = 0;
            while(0<(length=reader.read(chars))){
                builder.append(chars, 0, length);
            }
            return builder.toString();
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            httpclient.getConnectionManager().shutdown();  //释放连接 
        }
        return null;
    }

HttpClient 使用 POST 方法下载网页

例子:按城市抓取酒店信息,http://xxx.aspx

<form name="aspnetForm" method="post" action="SearchHotel.aspx" id="aspnetFrom">
    <input type="hidden" name="cityId" value="" />
    <input type="hidden" name="checkIn" value="" />
    <input type="hidden" name="checkOut" value="" />
</form>

由于 POST 方法需要提交的三个参数分别包括键和值,NameValuePair 是一个接口,而 BasicNameValuePair 则是这个接口的实现,使用 BasicNameValuePair 封装键值对,例如 参数 cityId 对应的值是 1,代码如下所示

new BasicNameValuePair("cityId", "1");
HttpClient httpclient = new DefaultHttpClient();

//使用 HttpPost 发送 POST 请求
HttpPost httppost = newPost("http://xxx.aspx");
//POST 数据
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);  // 3 个参数
nameValuePairs.add(new BasicNameValuePair("checkIn", "2011-4-15"));    //入住日期
nameValuePairs.add(new BasicNameValuePair("checkOut", "2011-4-25"));   //离店日期
nameValuePairs.add(new BasicNameValuePair("cityId", "1"));             //城市编码
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

//执行 HTTP POST 请求
HttpResponse response = httpclient.execute(httppost);

//取得内容流
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);

//按字节读入内容流到字节数组缓存
int current = 0;
while((current=bis.read()) != -1){
    baf.append((byte) current);
}
String text = new String(baf.toByteArray(), "utf-8");  //指定编码
System.out.println(text);

//当不再需要 HttpClient 实例时,关闭连接管理器,以确保立即释放所有系统资源
httpclient.getConnectionManager().shutdown();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值