HttpClient4基础1--通过匿名代理访问网页

23 篇文章 0 订阅

HttpClient发布4.0了 而且底层完全重写了,据说无论是效率还是结构都有质的飞跃。

HttpClient4--通过匿名代理访问网页

现在也要与时具进,研究研究。
package test.httpclient4.proxy;   
  
import java.io.BufferedReader;   
import java.io.IOException;   
import java.io.InputStreamReader;   
  
import org.apache.http.HttpEntity;   
import org.apache.http.HttpHost;   
import org.apache.http.HttpResponse;   
import org.apache.http.HttpStatus;   
import org.apache.http.StatusLine;   
import org.apache.http.client.ClientProtocolException;   
import org.apache.http.client.HttpClient;   
import org.apache.http.client.methods.HttpGet;   
import org.apache.http.conn.params.ConnRoutePNames;   
import org.apache.http.impl.client.DefaultHttpClient;   
import org.apache.http.message.BasicStatusLine;   
import org.apache.http.util.EntityUtils;   
  
  
public class GetHttpByProxy {   
  
    public static void main(String[] args) throws ClientProtocolException,   
            IOException {   
        //实例化一个HttpClient   
        HttpClient httpClient = new DefaultHttpClient();   
        //设定目标站点   
        HttpHost httpHost = new HttpHost("www.shanhe114.com");   
        //设置代理对象 ip/代理名称,端口   
        HttpHost proxy = new HttpHost("192.168.1.28", 5608);   
        //对HttpClient对象设置代理   
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,   
                proxy);   
        HttpGet httpGet = new HttpGet("/");   
        //这里也可以直接使用httpGet的绝对地址,当然如果不是具体地址不要忘记/结尾   
        //HttpGet httpGet = new HttpGet("http://www.shanhe114.com/");   
        //HttpResponse response = httpClient.execute(httpGet);   
           
        HttpResponse response = httpClient.execute(httpHost, httpGet);   
        if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){   
            //请求成功   
            //取得请求内容   
            HttpEntity entity = response.getEntity();   
            //显示内容   
            if (entity != null) {   
                // 显示结果   
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity   
                        .getContent(), "UTF-8"));   
                String line = null;   
                StringBuffer strBuf = new StringBuffer((int) entity.getContentLength());   
                while ((line = reader.readLine()) != null) {   
                    strBuf.append(line);   
                }   
                strBuf.trimToSize();   
                System.out.println(strBuf.toString());   
            }   
            if (entity != null) {   
                entity.consumeContent();   
            }   
        }   
    }   
}  

对于显示将结果转换成String以备后续使用,HttpClient已经为我们提供了一个简便方法

如下


System.out.println(EntityUtils.toString(entity,"utf-8"));  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值