• httpClient 入门实例


    1. import java.io.File;  
    2. import java.io.FileInputStream;  
    3. import java.io.IOException;  
    4. import java.io.UnsupportedEncodingException;  
    5. import java.security.KeyManagementException;  
    6. import java.security.KeyStore;  
    7. import java.security.KeyStoreException;  
    8. import java.security.NoSuchAlgorithmException;  
    9. import java.security.cert.CertificateException;  
    10. import java.util.ArrayList;  
    11. import java.util.List;  
    12.   
    13. import javax.net.ssl.SSLContext;  
    14.   
    15. import org.apache.http.HttpEntity;  
    16. import org.apache.http.NameValuePair;  
    17. import org.apache.http.ParseException;  
    18. import org.apache.http.client.ClientProtocolException;  
    19. import org.apache.http.client.entity.UrlEncodedFormEntity;  
    20. import org.apache.http.client.methods.CloseableHttpResponse;  
    21. import org.apache.http.client.methods.HttpGet;  
    22. import org.apache.http.client.methods.HttpPost;  
    23. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
    24. import org.apache.http.conn.ssl.SSLContexts;  
    25. import org.apache.http.conn.ssl.TrustSelfSignedStrategy;  
    26. import org.apache.http.entity.ContentType;  
    27. import org.apache.http.entity.mime.MultipartEntityBuilder;  
    28. import org.apache.http.entity.mime.content.FileBody;  
    29. import org.apache.http.entity.mime.content.StringBody;  
    30. import org.apache.http.impl.client.CloseableHttpClient;  
    31. import org.apache.http.impl.client.HttpClients;  
    32. import org.apache.http.message.BasicNameValuePair;  
    33. import org.apache.http.util.EntityUtils;  
    34. import org.junit.Test;  
    35.   
    36. public class HttpClientTest {  
    37.   
    38.     @Test  
    39.     public void jUnitTest() {  
    40.         get();  
    41.     }  
    42.   
    43.     /** 
    44.      * HttpClient连接SSL 
    45.      */  
    46.     public void ssl() {  
    47.         CloseableHttpClient httpclient = null;  
    48.         try {  
    49.             KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
    50.             FileInputStream instream = new FileInputStream(new File("d:\tomcat.keystore"));  
    51.             try {  
    52.                 // 加载keyStore d:\tomcat.keystore    
    53.                 trustStore.load(instream, "123456".toCharArray());  
    54.             } catch (CertificateException e) {  
    55.                 e.printStackTrace();  
    56.             } finally {  
    57.                 try {  
    58.                     instream.close();  
    59.                 } catch (Exception ignore) {  
    60.                 }  
    61.             }  
    62.             // 相信自己的CA和所有自签名的证书  
    63.             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();  
    64.             // 只允许使用TLSv1协议  
    65.             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,  
    66.                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);  
    67.             httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();  
    68.             // 创建http请求(get方式)  
    69.             HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");  
    70.             System.out.println("executing request" + httpget.getRequestLine());  
    71.             CloseableHttpResponse response = httpclient.execute(httpget);  
    72.             try {  
    73.                 HttpEntity entity = response.getEntity();  
    74.                 System.out.println("----------------------------------------");  
    75.                 System.out.println(response.getStatusLine());  
    76.                 if (entity != null) {  
    77.                     System.out.println("Response content length: " + entity.getContentLength());  
    78.                     System.out.println(EntityUtils.toString(entity));  
    79.                     EntityUtils.consume(entity);  
    80.                 }  
    81.             } finally {  
    82.                 response.close();  
    83.             }  
    84.         } catch (ParseException e) {  
    85.             e.printStackTrace();  
    86.         } catch (IOException e) {  
    87.             e.printStackTrace();  
    88.         } catch (KeyManagementException e) {  
    89.             e.printStackTrace();  
    90.         } catch (NoSuchAlgorithmException e) {  
    91.             e.printStackTrace();  
    92.         } catch (KeyStoreException e) {  
    93.             e.printStackTrace();  
    94.         } finally {  
    95.             if (httpclient != null) {  
    96.                 try {  
    97.                     httpclient.close();  
    98.                 } catch (IOException e) {  
    99.                     e.printStackTrace();  
    100.                 }  
    101.             }  
    102.         }  
    103.     }  
    104.   
    105.     /** 
    106.      * post方式提交表单(模拟用户登录请求) 
    107.      */  
    108.     public void postForm() {  
    109.         // 创建默认的httpClient实例.    
    110.         CloseableHttpClient httpclient = HttpClients.createDefault();  
    111.         // 创建httppost    
    112.         HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");  
    113.         // 创建参数队列    
    114.         List<namevaluepair> formparams = new ArrayList<namevaluepair>();  
    115.         formparams.add(new BasicNameValuePair("username", "admin"));  
    116.         formparams.add(new BasicNameValuePair("password", "123456"));  
    117.         UrlEncodedFormEntity uefEntity;  
    118.         try {  
    119.             uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
    120.             httppost.setEntity(uefEntity);  
    121.             System.out.println("executing request " + httppost.getURI());  
    122.             CloseableHttpResponse response = httpclient.execute(httppost);  
    123.             try {  
    124.                 HttpEntity entity = response.getEntity();  
    125.                 if (entity != null) {  
    126.                     System.out.println("--------------------------------------");  
    127.                     System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));  
    128.                     System.out.println("--------------------------------------");  
    129.                 }  
    130.             } finally {  
    131.                 response.close();  
    132.             }  
    133.         } catch (ClientProtocolException e) {  
    134.             e.printStackTrace();  
    135.         } catch (UnsupportedEncodingException e1) {  
    136.             e1.printStackTrace();  
    137.         } catch (IOException e) {  
    138.             e.printStackTrace();  
    139.         } finally {  
    140.             // 关闭连接,释放资源    
    141.             try {  
    142.                 httpclient.close();  
    143.             } catch (IOException e) {  
    144.                 e.printStackTrace();  
    145.             }  
    146.         }  
    147.     }  
    148.   
    149.     /** 
    150.      * 发送 post请求访问本地应用并根据传递参数不同返回不同结果 
    151.      */  
    152.     public void post() {  
    153.         // 创建默认的httpClient实例.    
    154.         CloseableHttpClient httpclient = HttpClients.createDefault();  
    155.         // 创建httppost    
    156.         HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");  
    157.         // 创建参数队列    
    158.         List<namevaluepair> formparams = new ArrayList<namevaluepair>();  
    159.         formparams.add(new BasicNameValuePair("type", "house"));  
    160.         UrlEncodedFormEntity uefEntity;  
    161.         try {  
    162.             uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
    163.             httppost.setEntity(uefEntity);  
    164.             System.out.println("executing request " + httppost.getURI());  
    165.             CloseableHttpResponse response = httpclient.execute(httppost);  
    166.             try {  
    167.                 HttpEntity entity = response.getEntity();  
    168.                 if (entity != null) {  
    169.                     System.out.println("--------------------------------------");  
    170.                     System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));  
    171.                     System.out.println("--------------------------------------");  
    172.                 }  
    173.             } finally {  
    174.                 response.close();  
    175.             }  
    176.         } catch (ClientProtocolException e) {  
    177.             e.printStackTrace();  
    178.         } catch (UnsupportedEncodingException e1) {  
    179.             e1.printStackTrace();  
    180.         } catch (IOException e) {  
    181.             e.printStackTrace();  
    182.         } finally {  
    183.             // 关闭连接,释放资源    
    184.             try {  
    185.                 httpclient.close();  
    186.             } catch (IOException e) {  
    187.                 e.printStackTrace();  
    188.             }  
    189.         }  
    190.     }  
    191.   
    192.     /** 
    193.      * 发送 get请求 
    194.      */  
    195.     public void get() {  
    196.         CloseableHttpClient httpclient = HttpClients.createDefault();  
    197.         try {  
    198.             // 创建httpget.    
    199.             HttpGet httpget = new HttpGet("http://www.baidu.com/");  
    200.             System.out.println("executing request " + httpget.getURI());  
    201.             // 执行get请求.    
    202.             CloseableHttpResponse response = httpclient.execute(httpget);  
    203.             try {  
    204.                 // 获取响应实体    
    205.                 HttpEntity entity = response.getEntity();  
    206.                 System.out.println("--------------------------------------");  
    207.                 // 打印响应状态    
    208.                 System.out.println(response.getStatusLine());  
    209.                 if (entity != null) {  
    210.                     // 打印响应内容长度    
    211.                     System.out.println("Response content length: " + entity.getContentLength());  
    212.                     // 打印响应内容    
    213.                     System.out.println("Response content: " + EntityUtils.toString(entity));  
    214.                 }  
    215.                 System.out.println("------------------------------------");  
    216.             } finally {  
    217.                 response.close();  
    218.             }  
    219.         } catch (ClientProtocolException e) {  
    220.             e.printStackTrace();  
    221.         } catch (ParseException e) {  
    222.             e.printStackTrace();  
    223.         } catch (IOException e) {  
    224.             e.printStackTrace();  
    225.         } finally {  
    226.             // 关闭连接,释放资源    
    227.             try {  
    228.                 httpclient.close();  
    229.             } catch (IOException e) {  
    230.                 e.printStackTrace();  
    231.             }  
    232.         }  
    233.     }  
    234.   
    235.     /** 
    236.      * 上传文件 
    237.      */  
    238.     public void upload() {  
    239.         CloseableHttpClient httpclient = HttpClients.createDefault();  
    240.         try {  
    241.             HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");  
    242.   
    243.             FileBody bin = new FileBody(new File("F:\image\sendpix0.jpg"));  
    244.             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);  
    245.   
    246.             HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();  
    247.   
    248.             httppost.setEntity(reqEntity);  
    249.   
    250.             System.out.println("executing request " + httppost.getRequestLine());  
    251.             CloseableHttpResponse response = httpclient.execute(httppost);  
    252.             try {  
    253.                 System.out.println("----------------------------------------");  
    254.                 System.out.println(response.getStatusLine());  
    255.                 HttpEntity resEntity = response.getEntity();  
    256.                 if (resEntity != null) {  
    257.                     System.out.println("Response content length: " + resEntity.getContentLength());  
    258.                 }  
    259.                 EntityUtils.consume(resEntity);  
    260.             } finally {  
    261.                 response.close();  
    262.             }  
    263.         } catch (ClientProtocolException e) {  
    264.             e.printStackTrace();  
    265.         } catch (IOException e) {  
    266.             e.printStackTrace();  
    267.         } finally {  
    268.             try {  
    269.                 httpclient.close();  
    270.             } catch (IOException e) {  
    271.                 e.printStackTrace();  
    272.             }  
    273.         }  
    274.     }  
    275. }
  • 相关阅读:
    string基本字符系列容器(一)
    HDU 1541 star (树状数组)
    NKOI 1321--数列操作问题(裸BIT)
    树状数组(BIT)初学
    vector向量容器
    C++ STL概述
    2015年,为ACM奋斗的一年
    kuangbin带你飞,矩阵(简单数学推导题)
    hust 1009 Sum the K-th
    hust 1223 Friends
  • 原文地址:https://www.cnblogs.com/Struts-pring/p/4303794.html
Copyright © 2020-2023  润新知