0
点赞
收藏
分享

微信扫一扫

http post传递map

代码小姐 2022-04-03 阅读 30
java后端

记一次踩坑经历,话不多说上代码
遇到传递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>

欢迎大佬指点

举报

相关推荐

0 条评论