zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    js中取整数的方法
    js中原型和原型链
    js中获取class封装
    Cocos2dx打包成apk包时在手机上闪退
    计算两个日期间相差的天数
    Stealing a Cake [函数方程符合凸性 三分]
    插件式架构设计(转)
    转:Entity FrameWork利用Database.SqlQuery<T>执行存储过程并返回参数
    后台web请求代码(含https,json提交)
    sitecore 缓存管理器
  • 原文地址:https://www.cnblogs.com/g120/p/14835340.html
Copyright © 2011-2022 走看看