码迷,mamicode.com
首页 > 编程语言 > 详细

Java实现HTTP GET 通过 Body 来发送数据

时间:2021-06-02 19:32:23      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:uri   end   https   系统   请求方式   ==   over   ast   style   

在开发过程中和第三方系统对接时遇到需要使用GET请求传递JSON参数,现整理请求方式如下。

重写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;
    }
}

 

Java实现HTTP GET 通过 Body 来发送数据

标签:uri   end   https   系统   请求方式   ==   over   ast   style   

原文地址:https://www.cnblogs.com/g120/p/14835340.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!