HttpClient 学习笔记--源自技术

 HttpClient 是 Apache提供的一个HTTP连接工具包

  网址:http://hc.apache.org/

  4.5jar包下载:httpclient 4.5

  4.5src包下载:httpclient 4.5-src


[java]  view plain  copy
  1.   /*基本的get请求*/  
  2.   public final static void basicGet() throws ClientProtocolException, IOException{  
  3.       CloseableHttpClient httpclient = HttpClients.createDefault();  
  4.       try {  
  5.           HttpGet httpget = new HttpGet("http://www.weather.com.cn/data/sk/101010100.html");  
  6.           CloseableHttpResponse response = httpclient.execute(httpget);  
  7.           try {  
  8.             StatusLine statusLine = response.getStatusLine();  
  9.             System.out.println(statusLine);  
  10.               
  11.             HttpEntity resEntity = response.getEntity();  
  12.             InputStream content = resEntity.getContent();  
  13.             InputStreamReader reader = new InputStreamReader(content);  
  14.             BufferedReader bufferedReader = new BufferedReader(reader);  
  15.             String lineTxt = null;  
  16.               while((lineTxt = bufferedReader.readLine()) != null){  
  17.                   System.out.println(lineTxt);  
  18.               }  
  19.               //调用中止请求对象  
  20.               httpget.abort();  
  21.           } finally {  
  22.               response.close();  
  23.           }  
  24.       } finally {  
  25.           httpclient.close();  
  26.       }  
  27.   }  
  28.     
  29.   /*基本的Post请求*/  
  30.   public final static void basicPost() throws ClientProtocolException, IOException{  
  31.     CloseableHttpClient httpclient = HttpClients.createDefault();  
  32.     try {  
  33.         HttpPost httppost = new HttpPost("http://www.apache.org/");  
  34.         CloseableHttpResponse response = httpclient.execute(httppost);  
  35.         try {  
  36.             StatusLine statusLine = response.getStatusLine();  
  37.             System.out.println(statusLine);  
  38.               
  39.             HttpEntity resEntity = response.getEntity();  
  40.             InputStream content = resEntity.getContent();  
  41.             InputStreamReader reader = new InputStreamReader(content);  
  42.             BufferedReader bufferedReader = new BufferedReader(reader);  
  43.             String lineTxt = null;  
  44.             while((lineTxt = bufferedReader.readLine()) != null){  
  45.                 System.out.println(lineTxt);  
  46.             }  
  47.               
  48.             //调用中止请求对象  
  49.             httppost.abort();  
  50.         } finally {  
  51.             response.close();  
  52.         }  
  53.     } finally {  
  54.         httpclient.close();  
  55.     }  
  56.   }  
  57.     
  58.   /*带参数的Post请求*/  
  59.   public final static void parameterPost() throws IOException{  
  60.     CloseableHttpClient httpClient = HttpClients.createDefault();  
  61.     try {  
  62.         HttpPost httpPost = new HttpPost("http://www.imooc.com/user/login");  
  63.         List <NameValuePair> nvps = new ArrayList <NameValuePair>();  
  64.         nvps.add(new BasicNameValuePair("username""u"));  
  65.         nvps.add(new BasicNameValuePair("password""p"));  
  66.         httpPost.setEntity(new UrlEncodedFormEntity(nvps));  
  67.         CloseableHttpResponse response = httpClient.execute(httpPost);  
  68.     try {  
  69.         System.out.println(response.getStatusLine());  
  70.         System.out.println("Response content: " + EntityUtils.toString(response.getEntity(), "UTF-8"));   
  71.         //调用中止请求对象  
  72.         httpPost.abort();  
  73.     }finally{  
  74.         response.close();  
  75.     }  
  76. }finally{  
  77.     httpClient.close();  
  78. }  
  79.   }  
  80.     
  81.   /* 上传文件 
  82.    * 示例:ClientMultipartFormPost.java 
  83.    * */  
  84.   public final static void upload() throws IOException{  
  85.     CloseableHttpClient httpClient = HttpClients.createDefault();  
  86.     try{  
  87.         HttpPost httpPost = new HttpPost("http://image.baidu.com/pictureup/uploadshitu?fr=flash&fm=index&pos=upload");  
  88.         FileBody bin = new FileBody(new File("C:\\Users\\Administrator\\Downloads\\123.png"));  
  89.           
  90.         StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);  
  91.         HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("fileName", bin).addPart("comment", comment).build();  
  92.         httpPost.setEntity(reqEntity);  
  93.         CloseableHttpResponse response = httpClient.execute(httpPost);  
  94.         try {  
  95.             HttpEntity resEntity = response.getEntity();  
  96.               if (resEntity != null) {  
  97.                 System.out.println(response.getStatusLine());  
  98.                   System.out.println("Response content length: " + resEntity.getContentLength());  
  99.               }  
  100.               EntityUtils.consume(resEntity);  
  101.     } finally{  
  102.         response.close();  
  103.     }  
  104.     }finally{  
  105.         httpClient.close();  
  106.     }  
  107.   }  
  108.     
  109.   /* SSL 
  110.    * 示例:ClientCustomSSL.java 
  111.    * */  
  112.   public final static void ssl() throws Exception {  
  113.     // Trust own CA and all self-signed certs  
  114.       SSLContext sslcontext = SSLContexts.custom()  
  115.               .loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),  
  116.                       new TrustSelfSignedStrategy())  
  117.               .build();  
  118.       // Allow TLSv1 protocol only  
  119.       SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
  120.               sslcontext,  
  121.               new String[] { "TLSv1" },  
  122.               null,  
  123.               SSLConnectionSocketFactory.getDefaultHostnameVerifier());  
  124.       CloseableHttpClient httpclient = HttpClients.custom()  
  125.               .setSSLSocketFactory(sslsf)  
  126.               .build();  
  127.       try {  
  128.   
  129.           HttpGet httpget = new HttpGet("https://localhost/");  
  130.   
  131.           System.out.println("executing request " + httpget.getRequestLine());  
  132.   
  133.           CloseableHttpResponse response = httpclient.execute(httpget);  
  134.           try {  
  135.               HttpEntity entity = response.getEntity();  
  136.   
  137.               System.out.println("----------------------------------------");  
  138.               System.out.println(response.getStatusLine());  
  139.               EntityUtils.consume(entity);  
  140.           } finally {  
  141.               response.close();  
  142.           }  
  143.       } finally {  
  144.           httpclient.close();  
  145.       }  
  146.   }  
  147.     
  148.   /* HTTP上下文 
  149.    * 示例:ClientCustomContext.java 
  150.    **/  
  151.   public final static void context() throws Exception {  
  152.     CloseableHttpClient httpclient = HttpClients.createDefault();  
  153.       try {  
  154.           // 创建一个cookie存储的实例  
  155.           CookieStore cookieStore = new BasicCookieStore();  
  156.             
  157.           // 创建本地HTTP上下文  
  158.           HttpClientContext localContext = HttpClientContext.create();  
  159.           // 绑定定义cookie存储到上下文  
  160.           localContext.setCookieStore(cookieStore);  
  161.   
  162.           HttpGet httpget = new HttpGet("http://www.baidu.com/");  
  163.   
  164.           // 将上下文作为参数  
  165.           CloseableHttpResponse response = httpclient.execute(httpget, localContext);  
  166.           try {  
  167.               System.out.println("----------------------------------------");  
  168.               System.out.println(response.getStatusLine());  
  169.               List<Cookie> cookies = cookieStore.getCookies();  
  170.               for (int i = 0; i < cookies.size(); i++) {  
  171.                   System.out.println("Local cookie: " + cookies.get(i));  
  172.               }  
  173.               EntityUtils.consume(response.getEntity());  
  174.           } finally {  
  175.               response.close();  
  176.           }  
  177.       } finally {  
  178.           httpclient.close();  
  179.       }  
  180.   }  


推荐博文

博文1

博文2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值