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. }  

 

您好,您知道这么设置以后,如何设置代理服务器的用户名和密码么

好久没搞这个了,手边也没有这个环境,但是我帮你查了一下,请试试

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对象。


具体用法如下:

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;
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值