Java實現HTTP GET 通過 Body 來發送數據


在開發過程中和第三方系統對接時遇到需要使用GET請求傳遞JSON參數,現整理請求方式如下。

POM

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

 

重寫HttpGetWithEntity類

 1 public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
 2     public final static String METHOD_NAME = "GET";
 3 
 4     public HttpGetWithEntity() {
 5         super();
 6     }
 7 
 8     public HttpGetWithEntity(final URI uri) {
 9         super();
10         setURI(uri);
11     }
12     
13     public HttpGetWithEntity(final String uri) {
14         super();
15         setURI(URI.create(uri));
16     }
17 
18     @Override
19     public String getMethod() {
20     // TODO Auto-generated method stub
21         return METHOD_NAME;
22     }
23 
24 }

調用方法

public class test {
    public static JSONObject processGetWithBody(String url, Map<String, Object> args,String charset) {
        String defaultCharset = "UTF-8";
        JSONObject result = new JSONObject();
        HttpGetWithEntity getWithEntity = new HttpGetWithEntity(url);
        JSONObject params = new JSONObject();
        for (Map.Entry<String, Object> entry : args.entrySet()) {
            params.put(entry.getKey(), entry.getValue());
        }
        HttpEntity httpEntity = new StringEntity(params.toJSONString(), ContentType.APPLICATION_JSON);
        getWithEntity.setEntity(httpEntity);
        try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(getWithEntity)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                result = JSONObject.parseObject(EntityUtils.toString(responseEntity, StringUtils.hasText(charset) ? charset : defaultCharset));
            } else {
                // TODO:請求失敗邏輯
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

 

參考:

https://blog.csdn.net/HermitSun/article/details/89889743

https://blog.csdn.net/tianxingyun/article/details/116419354


免責聲明!

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



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