首页 > 其他分享 >httpclient实现HttpGet请求传body的json参数的!

httpclient实现HttpGet请求传body的json参数的!

时间:2022-10-07 14:46:14浏览次数:67  
标签:body HttpGet http String url json import 请求

原文来自:https://admins.blog.csdn.net/article/details/109809386

前言
最近调用公司项目一个接口时,发现该接口是一个Get请求,入参在Body 中(json格式)。场景如下:A服务需发送http请求调用B服务的接口(该接口为Get方式,入参是一个json字符串在body中传递)
当我看到这个接口的时候,感觉好奇怪(MMP,干嘛不用POST请求。Get就get,请求还放Body中,心里有些不爽)尽管心里不爽,但是也只能默默接受,撸起袖子 “干” 就完了!

实现过程:
首先官方不推荐这样做,但是http(基于tcp的超文本传输协议)并没有规定,Get 请求不能加body
一.首先我写了一个Get请求接口,本地测试一下,便于大家直观的理解

 

 

 

 本地使用postman调用是成功的,接下来我们使用Java代码请求调用
二.使用Http工具类调用Get请求(json参数)
1.引入httpclient 依赖

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>

2.定义一个HttpGet实体类

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
/**
* @author xf
* @version 1.0.0
* @ClassName HttpGetWithEntity
* @Description TODO 定义一个带body的GET请求 继承 HttpEntityEnclosingRequestBase
* @createTime 2020.11.18 13:51
*/
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
private final static String METHOD_NAME = "GET";

@Override
public String getMethod() {
return METHOD_NAME;
}
public HttpGetWithEntity() {
super();
}
public HttpGetWithEntity(final URI uri) {
super();
setURI(uri);
}
HttpGetWithEntity(final String uri) {
super();
setURI(URI.create(uri));
}

}

3.HttpGet请求公共方法

/**
* 发送get请求,参数为json
* @param url
* @param param
* @param encoding
* @return
* @throws Exception
*/
public static String sendJsonByGetReq(String url, String param, String encoding) throws Exception {
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
HttpEntity httpEntity = new StringEntity(param, ContentType.APPLICATION_JSON);
httpGetWithEntity.setEntity(httpEntity);
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpGetWithEntity);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
//释放链接
response.close();
return body;
}

4.运行服务,本地测试调用一下该接口


/**
* 测试 Get 请求
*/
@Test
public void test(){
String url = "http://127.0.0.1:8012/export/getByBodyJson";
Map<String, Object> map = new HashMap<>();
map.put("stuName","张一山");
map.put("school","北京戏剧学院");
String reqParams = JSONArray.toJSON(map).toString();
try {
String s = sendJsonByGetReq(url, reqParams, "UTF-8");
System.out.println("请求Get请求返回结果:"+s);
} catch (Exception e) {
e.printStackTrace();
}
}

三.使用HttpGet请求发送body入参调用成功

 

package com.utils.httpclient;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class HttpClientUtil {

    //发送请求的url
//    public static String url = "http://192.168.9.247:3080/co/cmd/deleteProject";
    /**
     * @Author: yc
     * @Description: HttpClient发送Post请求 携带json参数
     * @Date: 2022/10/07/18:32
     */
    public static String jsonPost(String url, JSONObject json) throws IOException {
        String content=null;
        // 获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 声明Post请求
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头,在Post请求中限制了浏览器后才能访问
//        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36");
        httpPost.addHeader("Accept", "*/*");
//        httpPost.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        httpPost.addHeader("Connection", "keep-alive");

        // 省略前面声明请求、设置Header等操作,直接从传递参数开始
        //        JSONObject json = new JSONObject();
        //     json.put("filePath","js");
        //     json.put("projectId","61020ccdfd33d86b6abe8745");
        //     json.put("type","fileFolder");
        //     
        //       将参数放到Post中
        //        通过new StringEntity(),可将Content-Type设置为text/plain类型
        //        httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));


        httpPost.setEntity(new StringEntity(json.toString(), "UTF-8"));

        // 发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();

            // 获取返回的信息
            content = EntityUtils.toString(entity, "UTF-8");
            System.out.println("获取的值为:"+content);

        } else {
            System.out.println("访问失败!!!");
        }

        // 关闭response、HttpClient资源
        response.close();
        httpClient.close();
        return content;
    }


    /**
     * 发送get请求,参数为json
     * @param url
     * @param param
     * @param encoding
     * @return
     * @throws Exception
     */
    public static String sendJsonByGetReq(String url, String param, String encoding) throws Exception {
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
        HttpEntity httpEntity = new StringEntity(param, ContentType.APPLICATION_JSON);
        httpGetWithEntity.setEntity(httpEntity);
        //执行请求操作,并拿到结果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpGetWithEntity);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        //释放链接
        response.close();
        return body;
    }


    public static void main(String[] args) throws IOException {
            String url="http://168.1.15.43:8003/localEndPoint?name=123";
//            JSONObject jsonObject=new JSONObject();
//            jsonObject.put("aa","123");
//            String aa=HttpClientUtil.jsonPost(url,jsonObject);
//            System.out.println(aa);
//
//        String url = "http://127.0.0.1:8012/export/getByBodyJson";
        Map<String, Object> map = new HashMap<>();
        map.put("stuName","张一山");
        map.put("school","北京戏剧学院");
        String reqParams = JSONArray.toJSON(map).toString();
        try {
            String s = sendJsonByGetReq(url, reqParams, "UTF-8");
            System.out.println("请求Get请求返回结果:"+s);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



}

 

标签:body,HttpGet,http,String,url,json,import,请求
From: https://www.cnblogs.com/rerise/p/16759684.html

相关文章

  • HttpClient发送Post请求传递json、普通参数
    importcom.alibaba.fastjson.JSONObject;importorg.apache.http.HttpEntity;importorg.apache.http.NameValuePair;importorg.apache.http.client.entity.UrlEncod......
  • Springboot 之 Filter 实现 Gzip 压缩超大 json 对象
    简介在项目中,存在传递超大json数据的场景。直接传输超大json数据的话,有以下两个弊端占用网络带宽,而有些云产品就是按照带宽来计费的,间接浪费了钱传输数据大导致......
  • JSON
    json在线解析:https://www.sojson.com/json基础入门:https://blog.csdn.net/Rao_Limon/article/details/80011601学习网站:http://c.biancheng.net/json/what-is-json.html......
  • .Net WebApi 中的 FromBody FromForm FromQuery FromHeader FromRoute
    在日常后端Api开发中,我们跟前端的沟通中,通常需要协商好入参的数据类型,和参数是通过什么方式存在于请求中的,是表单(form)、请求体(body)、地址栏参数(query)、还是说通过请求......
  • jsonschema2pojo 基于json schema 生成代码
    jsonschema2pojo是一个很不错的基于jsonschema生成代码的包以及工具(maven扩展)jsonschema2pojo特点支持基本的jsonschema操作支持java扩展,比如别名,继承扩展接口外......
  • quicklib json序列
    quicklibjson序列quicklib面向MODEL的JSON序列。unitUnit2;///<author>cxg2022-6-14</author>interfaceusesquick.Json.Serializer,Quick.MemoryCache.Seri......
  • openmetadata jsonschema 处理的一些变动
    openmetadata估计是因为quicktype使用复杂费事,最近版本quicktype的集成已经废弃了,都使用jsonschema2pojo了实际上使用jsonschema2pojo对于java项目来说也比较好,毕竟......
  • Android中的JSON详细总结
    1、JSON(JavaScriptObjectNotation)定义:一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案(有点类似于正则表达式,获得......
  • vue res.data接收到的是字符串的处理方式,先转化成Json格式再解析
    api.postWachPay(param).then(res=>{this.html=res.data;letdata=JSON.parse(res.data)console......
  • 就因为JSON.stringify,我的年终奖差点打水漂了
    本文已参与 「掘力星计划」 ,赢取创作大礼包,挑战创作激励金。前言「欢迎在评论区讨论,掘金官方将在掘力星计划活动结束后,在评论区抽送100份掘金周边,抽奖详情见活动文章」......