http post传递map

记一次踩坑经历,话不多说上代码
遇到传递list、map时,先想到的是转json然后toString,身为懒人的我就受不了,与是就有了下面的结果,顿时感觉舒服了许多

public static JSONObject doPost(String url,Map<String, String> map) {
        JSONObject result = null;
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        Gson gson = new Gson();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type","application/json;charset=utf-8");
        httpPost.setHeader("Accept","application/json");
        try {
            httpPost.setEntity(new StringEntity(gson.toJson(map),"utf-8"));
            HttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK == statusCode) {// 如果响应码是 200
                result = JSONObject.fromObject(EntityUtils.toString(response.getEntity()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
  }

接收

@RequestBody Map<String, String> map

最后放上pom

		<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
		<dependency>
		    <groupId>com.google.code.gson</groupId>
		    <artifactId>gson</artifactId>
		    <version>2.8.5</version>
		</dependency>
		<!-- httpclient -->
		<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

欢迎大佬指点

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值