Java訪問http/https方法


特別提示:本人博客部分有參考網絡其他博客,但均是本人親手編寫過並驗證通過。如發現博客有錯誤,請及時提出以免誤導其他人,謝謝!歡迎轉載,但記得標明文章出處: http://www.cnblogs.com/mao2080/

1、問題描述

  有時候需要在Java后台去訪問其他系統api,這些接口可能是http或https的。在網上搜索了下,還不少人提問,但是有些過於繁瑣於是自己整理了一篇博客。

2、代碼樣例

  1、引入pom,版本一定要高一點的不然會報錯。

1      <dependency>
2         <groupId>org.apache.httpcomponents</groupId>
3         <artifactId>httpclient</artifactId>
4         <version>4.5.3</version>
5     </dependency>

  2、代碼例子

  1 package com.mao2080.util;
  2 
  3 import org.apache.http.HttpResponse;
  4 import org.apache.http.client.methods.HttpGet;
  5 import org.apache.http.client.methods.HttpPost;
  6 import org.apache.http.entity.StringEntity;
  7 import org.apache.http.impl.client.CloseableHttpClient;
  8 import org.apache.http.impl.client.HttpClients;
  9 import org.apache.http.util.EntityUtils;
 10 
 11 import java.util.HashMap;
 12 import java.util.Map;
 13 
 14 /**
 15  * HttpClient工具類
 16  */
 17 public class HttpClientUtil {
 18 
 19     /**請求編碼*/
 20     private static final String DEFAULT_CHARSET = "UTF-8";
 21 
 22     /**
 23      * 執行HTTP POST請求
 24      * @param url url
 25      * @param param 參數
 26      * @return
 27      */
 28     public static String httpPostWithJSON(String url, Map<String, ?> param) {
 29         CloseableHttpClient client = null;
 30         try {
 31             if(url == null || url.trim().length() == 0){
 32                 throw new Exception("URL is null");
 33             }
 34             HttpPost httpPost = new HttpPost(url);
 35             client = HttpClients.createDefault();
 36             if(param != null){
 37                 StringEntity entity = new StringEntity(JSONUtils.toJSONString(param), DEFAULT_CHARSET);//解決中文亂碼問題
 38                 entity.setContentEncoding(DEFAULT_CHARSET);
 39                 entity.setContentType("application/json");
 40                 httpPost.setEntity(entity);
 41             }
 42             HttpResponse resp = client.execute(httpPost);
 43             if(resp.getStatusLine().getStatusCode() == 200) {
 44                 return EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
 45             }
 46         } catch (Exception e) {
 47             e.printStackTrace();
 48         } finally {
 49             close(client);
 50         }
 51         return null;
 52     }
 53 
 54     /**
 55      * 執行HTTP GET請求
 56      * @param url url
 57      * @param param 參數
 58      * @return
 59      */
 60     public static String httpGetWithJSON(String url, Map<String, ?> param) {
 61         CloseableHttpClient client = null;
 62         try {
 63             if(url == null || url.trim().length() == 0){
 64                 throw new Exception("URL is null");
 65             }
 66             client = HttpClients.createDefault();
 67             if(param != null){
 68                 StringBuffer sb = new StringBuffer("?");
 69                 for (String key : param.keySet()){
 70                     sb.append(key).append("=").append(param.get(key)).append("&");
 71                 }
 72                 url = url.concat(sb.toString());
 73                 url = url.substring(0, url.length()-1);
 74             }
 75             HttpGet httpGet = new HttpGet(url);
 76             HttpResponse resp = client.execute(httpGet);
 77             if(resp.getStatusLine().getStatusCode() == 200) {
 78                 return EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
 79             }
 80         } catch (Exception e) {
 81             e.printStackTrace();
 82         } finally {
 83             close(client);
 84         }
 85         return null;
 86     }
 87 
 88     /**
 89      * 關閉HTTP請求
 90      * @param client
 91      */
 92     private static void close(CloseableHttpClient client){
 93         if(client == null){
 94             return;
 95         }
 96         try {
 97             client.close();
 98         } catch (Exception e) {
 99         }
100     }
101 
102     public static void main(String[] args) throws Exception {
103         Map param = new HashMap();
104         param.put("userName", "admin");
105         param.put("password", "mao2080");
106         String result = httpGetWithJSON("https://www.baidu.com/", param);
107         System.out.println("result:"+result);
108     }
109 
110 
111 }

  3、運行結果

  

3、參考網站

  https://www.cnblogs.com/Vdiao/p/5339487.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM