httpclient4.3 设置代理请求

设置代理请求

最近需要使用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. }

你可能感兴趣的:(java,httpclient)