一文告訴你如何使用java調用http接口


程序如下:

添加apache相關maven依賴:

1        <dependency>
2             <groupId>org.apache.commons</groupId>
3             <artifactId>commons-lang3</artifactId>
4             <version>3.7</version>
5         </dependency>    

POST請求如下:

  1 import com.alibaba.fastjson.JSONObject;
  2 import org.apache.http.HttpEntity;
  3 import org.apache.http.NameValuePair;
  4 import org.apache.http.client.entity.UrlEncodedFormEntity;
  5 import org.apache.http.client.methods.CloseableHttpResponse;
  6 import org.apache.http.client.methods.HttpGet;
  7 import org.apache.http.client.methods.HttpPost;
  8 import org.apache.http.client.utils.URIBuilder;
  9 import org.apache.http.entity.StringEntity;
 10 import org.apache.http.impl.client.CloseableHttpClient;
 11 import org.apache.http.impl.client.HttpClients;
 12 import org.apache.http.message.BasicHeader;
 13 import org.apache.http.message.BasicNameValuePair;
 14 import org.apache.http.util.EntityUtils;
 15 import org.slf4j.Logger;
 16 import org.slf4j.LoggerFactory;
 17 import java.util.ArrayList;
 18 import java.util.List;
 19 
 20 /**
 21  * HttpClient發送POST請求
 22  */
 23 public class HttpClientService {
 24 
 25 
 26     /**
 27      * 發送POST請求
 28      * @param url
 29      * @param map集合
 30      * @return JSON
 31      * @throws Exception
 32      */
 33     public static Object sendPost(String url,  Map<String, String> map) throws Exception{
 34         JSONObject jsonObject = null;
 35         CloseableHttpClient client = null;
 36         CloseableHttpResponse response = null;
 37         try{
 38             /**
 39              * 創建一個httpclient對象
 40              */
 41             client = HttpClients.createDefault();
 42             /**
 43              * 創建一個post對象
 44              */
 45             HttpPost post = new HttpPost(url);
 46 
 47             JSONObject jsonParam = new JSONObject();
 48             Set<String> set = map.keySet();
 49             for (String str : set) {//將Map轉換成JSONObject
 50                 jsonParam.put(str, map.get(str));
 51             }
 52             JSONArray jsonArray = new JSONArray();
 53             jsonArray.add(jsonParam);//將JSONObject轉換成JSONArray入參
 54 
 55             /**
 56              * 設置上傳byte[]數組文件流
 57             builder.addBinaryBody("data", byteOutStream.toByteArray(), ContentType.MULTIPART_FORM_DATA, "AudioFile.wav");
 58             HttpEntity entity = builder.build();
 59             */
 60 
 61             /**
 62              * 設置上傳單一對象
 63              */
 64             StringEntity entity = new StringEntity(jsonArray.toString(), "utf-8");
 65 
 66             /**
 67              * 設置請求的內容
 68              */
 69             post.setEntity(entity);
 70             /**
 71              * 設置請求的報文頭部的編碼
 72              */
 73             post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
 74             /**
 75              * 設置請求的報文頭部的編碼
 76              */
 77             post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
 78             /**
 79              * 執行post請求
 80              */
 81             response = client.execute(post);
 82             /**
 83              * 獲取響應碼
 84              */
 85             int statusCode = response.getStatusLine().getStatusCode();
 86             if (200 == statusCode){
 87                 /**
 88                  * 通過EntityUitls獲取返回內容
 89                  */
 90                 String result = EntityUtils.toString(response.getEntity(),"UTF-8");
 91                 /**
 92                  * 轉換成json,根據合法性返回json或者字符串
 93                  */
 94                 try{
 95                     jsonObject = JSONObject.parseObject(result);
 96                     return jsonObject;
 97                 }catch (Exception e){
 98                     return result;
 99                 }
100             }else{
101                 LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST請求失敗!");
102             }
103         }catch (Exception e){
104             LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e);
105         }finally {
106             response.close();
107             client.close();
108         }
109         return null;
110     }
111 
112 }

GET請求如下:

 1 import com.alibaba.fastjson.JSONObject;
 2 import org.apache.http.HttpEntity;
 3 import org.apache.http.NameValuePair;
 4 import org.apache.http.client.entity.UrlEncodedFormEntity;
 5 import org.apache.http.client.methods.CloseableHttpResponse;
 6 import org.apache.http.client.methods.HttpGet;
 7 import org.apache.http.client.methods.HttpPost;
 8 import org.apache.http.client.utils.URIBuilder;
 9 import org.apache.http.entity.StringEntity;
10 import org.apache.http.impl.client.CloseableHttpClient;
11 import org.apache.http.impl.client.HttpClients;
12 import org.apache.http.message.BasicHeader;
13 import org.apache.http.message.BasicNameValuePair;
14 import org.apache.http.util.EntityUtils;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
17 import java.util.ArrayList;
18 import java.util.List;
19 
20 /**
21  * HttpClient發送GET請求
22  */
23 public class HttpClientService {
24 
25 
26     /**
27      * 發送GET請求
28      * @param url請求url
29      * @param name請求參數
30      * @return JSON
31      * @throws Exception
32      */
33     public static Object sendGet(String url,String name) throws Exception{
34         JSONObject jsonObject = null;
35         CloseableHttpClient client = null;
36         CloseableHttpResponse response = null;
37         try{
38             /**
39              * 創建HttpClient對象
40              */
41             client = HttpClients.createDefault();
42             /**
43              * 創建URIBuilder
44              */
45             URIBuilder uriBuilder = new URIBuilder(url);
46             
47             /**
48              * 設置參數
49              */
50             uriBuilder.addParameters(name);
51             /**
52              * 創建HttpGet
53              */
54             HttpGet httpGet = new HttpGet(uriBuilder.build());
55             /**
56              * 設置請求頭部編碼
57              */
58             httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
59             /**
60              * 請求服務
61              */
62             response = client.execute(httpGet);
63             /**
64              * 獲取響應嗎
65              */
66             int statusCode = response.getStatusLine().getStatusCode();
67 
68             if (200 == statusCode){
69                 /**
70                  * 獲取返回對象
71                  */
72                 HttpEntity entity = response.getEntity();
73                 /**
74                  * 通過EntityUitls獲取返回內容
75                  */
76                 String result = EntityUtils.toString(entity,"UTF-8");
77                 /**
78                  * 轉換成json,根據合法性返回json或者字符串
79                  */
80                 try{
81                     jsonObject = JSONObject.parseObject(result);
82                     return jsonObject;
83                 }catch (Exception e){
84                     return result;
85                 }
86             }else{
87                 LOGGER.error("HttpClientService-line: {}, errorMsg{}", 97, "GET請求失敗!");
88             }
89         }catch (Exception e){
90             LOGGER.error("HttpClientService-line: {}, Exception: {}", 100, e);
91         } finally {
92             response.close();
93             client.close();
94         }
95         return null;
96     }
97    
98 }

文章參考:

參考鏈接一參考鏈接二參考鏈接三

 

總語:

我是南國以南i記錄點滴每天成長一點點,學習是永無止境的!轉載請附原文鏈接!!!


免責聲明!

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



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