httpclient4.X 设置代理请求(包含账号密码)

        最近需要使用Httpclient做后台请求,使用的是httpclient4.3版本,apache网站上有,我这里就不提供下载链接了,搜一下就可以了,废话少说,直接上代码:
Java代码   收藏代码
  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3.   
  4. import org.apache.http.HttpEntity;  
  5. import org.apache.http.HttpHost;  
  6. import org.apache.http.NameValuePair;  
  7. import org.apache.http.client.config.RequestConfig;  
  8. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  9. import org.apache.http.client.methods.CloseableHttpResponse;  
  10. import org.apache.http.client.methods.HttpPost;  
  11. import org.apache.http.impl.client.CloseableHttpClient;  
  12. import org.apache.http.impl.client.HttpClientBuilder;  
  13. import org.apache.http.message.BasicNameValuePair;  
  14. import org.apache.http.util.EntityUtils;  
  15.   
  16. public class HttpClientTest {  
  17.     public static void main(String args[]) throws Exception {  
  18.         // 创建HttpClientBuilder  
  19.         HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();  
  20.         // HttpClient  
  21.         CloseableHttpClient closeableHttpClient = httpClientBuilder.build();  
  22.         // 依次是目标请求地址,端口号,协议类型  
  23.         HttpHost target = new HttpHost("10.10.100.102:8080/mytest"8080,  
  24.                 "http");  
  25.         // 依次是代理地址,代理端口号,协议类型  
  26.         HttpHost proxy = new HttpHost("yourproxy"8080"http");  
  27.         RequestConfig config = RequestConfig.custom().setProxy(proxy).build();  
  28.   
  29.         // 请求地址  
  30.         HttpPost httpPost = new HttpPost("http://10.10.100.102:8080/mytest");  
  31.         httpPost.setConfig(config);  
  32.         // 创建参数队列  
  33.         List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
  34.         // 参数名为pid,值是2  
  35.         formparams.add(new BasicNameValuePair("pid""2"));  
  36.   
  37.         UrlEncodedFormEntity entity;  
  38.         try {  
  39.             entity = new UrlEncodedFormEntity(formparams, "UTF-8");  
  40.             httpPost.setEntity(entity);  
  41.             CloseableHttpResponse response = closeableHttpClient.execute(  
  42.                     target, httpPost);  
  43.             // getEntity()  
  44.             HttpEntity httpEntity = response.getEntity();  
  45.             if (httpEntity != null) {  
  46.                 // 打印响应内容  
  47.                 System.out.println("response:"  
  48.                         + EntityUtils.toString(httpEntity, "UTF-8"));  
  49.             }  
  50.             // 释放资源  
  51.             closeableHttpClient.close();  
  52.         } catch (Exception e) {  
  53.             e.printStackTrace();  
  54.         }  
  55.     }  
  56. }  

 

       那么,如何设置代理服务器的用户名和密码?请看如下代码:

  1. HttpHost proxy = new HttpHost("proxy"8080);  
  2.   
  3. BasicScheme proxyAuth = new BasicScheme();  
  4. // Make client believe the challenge came form a proxy  
  5. proxyAuth.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC realm=default"));  
  6. BasicAuthCache authCache = new BasicAuthCache();  
  7. authCache.put(proxy, proxyAuth);  
  8.   
  9. CredentialsProvider credsProvider = new BasicCredentialsProvider();  
  10. credsProvider.setCredentials(  
  11.         new AuthScope(proxy),  
  12.         new UsernamePasswordCredentials("username""password"));  
  13.   
  14. HttpClientContext context = HttpClientContext.create();  
  15. context.setAuthCache(authCache);  
  16. context.setCredentialsProvider(credsProvider);  
  17.   
  18. CloseableHttpClient httpclient = HttpClients.createDefault();  
  19. try {  
  20.     CloseableHttpResponse response = httpclient.execute(new HttpGet("/stuff"), context);  
  21.     try {  
  22.         // ...  
  23.     } finally {  
  24.         response.close();  
  25.     }  
  26. finally {  
  27.     httpclient.close();  
  28. }  
HttpHost proxy = new HttpHost("proxy", 8080);

BasicScheme proxyAuth = new BasicScheme();
// Make client believe the challenge came form a proxy
proxyAuth.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC realm=default"));
BasicAuthCache authCache = new BasicAuthCache();
authCache.put(proxy, proxyAuth);

CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
        new AuthScope(proxy),
        new UsernamePasswordCredentials("username", "password"));

HttpClientContext context = HttpClientContext.create();
context.setAuthCache(authCache);
context.setCredentialsProvider(credsProvider);

CloseableHttpClient httpclient = HttpClients.createDefault();
try {
    CloseableHttpResponse response = httpclient.execute(new HttpGet("/stuff"), context);
    try {
        // ...
    } finally {
        response.close();
    }
} finally {
    httpclient.close();
}

       使用代理需要导入:commons-logging-1.1.jar,httpclient-4.0-beta2.jar ,httpcore-4.1-alpha1.jar 和 commons-codec-1.4.jar架包。在连接代理时需要使用用户名和密码构造UsernamePasswordCredentials对象并作为参数传递给HttpClient对象。

 

具体用法如下:

  1. public static void main(String args[])  
  2. {  
  3.  StringBuffer sb = new StringBuffer();  
  4.  //创建HttpClient实例  
  5.  HttpClient client = getHttpClient();  
  6.  //创建httpGet  
  7.  HttpGet httpGet = new HttpGet("http://www.csdn.net");  
  8.  //执行  
  9.  try {  
  10.   HttpResponse response = client.execute(httpGet);  
  11.     
  12.   HttpEntity entry = response.getEntity();  
  13.     
  14.   if(entry != null)  
  15.   {  
  16.    InputStreamReader is = new InputStreamReader(entry.getContent());  
  17.    BufferedReader br = new BufferedReader(is);  
  18.    String str = null;  
  19.    while((str = br.readLine()) != null)  
  20.    {  
  21.     sb.append(str.trim());  
  22.    }  
  23.    br.close();  
  24.   }  
  25.     
  26.  } catch (ClientProtocolException e) {  
  27.   // TODO Auto-generated catch block  
  28.   e.printStackTrace();  
  29.  } catch (IOException e) {  
  30.   // TODO Auto-generated catch block  
  31.   e.printStackTrace();  
  32.  }  
  33.  System.out.println(sb.toString());  
  34. }  
  35. //设置代理  
  36. public static HttpClient getHttpClient() {  
  37.  DefaultHttpClient httpClient = new DefaultHttpClient();  
  38.  String proxyHost = "proxycn2.huawei.com";  
  39.  int proxyPort = 8080;  
  40.  String userName = "china\\******";  
  41.  String password = "*******“  
  42.  httpClient.getCredentialsProvider().setCredentials(  
  43.    new AuthScope(proxyHost, proxyPort),  
  44.    new UsernamePasswordCredentials(userName, password));  
  45.  HttpHost proxy = new HttpHost(proxyHost,proxyPort);  
  46.  httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);  
  47.  return httpClient;  
  48. }  
public static void main(String args[])
{
 StringBuffer sb = new StringBuffer();
 //创建HttpClient实例
 HttpClient client = getHttpClient();
 //创建httpGet
 HttpGet httpGet = new HttpGet("http://www.csdn.net");
 //执行
 try {
  HttpResponse response = client.execute(httpGet);
  
  HttpEntity entry = response.getEntity();
  
  if(entry != null)
  {
   InputStreamReader is = new InputStreamReader(entry.getContent());
   BufferedReader br = new BufferedReader(is);
   String str = null;
   while((str = br.readLine()) != null)
   {
    sb.append(str.trim());
   }
   br.close();
  }
  
 } catch (ClientProtocolException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 System.out.println(sb.toString());
}
//设置代理
public static HttpClient getHttpClient() {
 DefaultHttpClient httpClient = new DefaultHttpClient();
 String proxyHost = "proxycn2.huawei.com";
 int proxyPort = 8080;
 String userName = "china\\******";
 String password = "*******“
 httpClient.getCredentialsProvider().setCredentials(
   new AuthScope(proxyHost, proxyPort),
   new UsernamePasswordCredentials(userName, password));
 HttpHost proxy = new HttpHost(proxyHost,proxyPort);
 httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
 return httpClient;
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值