http post传递map

http post传递map
强烈推介IDEA2021.1.3破解激活,IntelliJ IDEA 注册码,2021.1.3IDEA 激活码  

大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说http post传递map,希望能够帮助大家进步!!!

  • 发送

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>
 

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/17852

发表评论