Discuss / Java / 原生发送post请求,携带json参数.

原生发送post请求,携带json参数.

Topic source

Loading...

#1 Created at ... [Delete] [Delete and Lock User]

原生发送post请求,携带json参数.这里需要用到下一节里面的一个第三方工具包。把map转为json字符串。不然手动转很麻烦

    @Test
    public void testPost() throws URISyntaxException, IOException, InterruptedException {
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI("http://xxxxx/login"))
                .timeout(Duration.ofSeconds(6000))
                // 设置Header:
//                .header("User-Agent", "Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0) like Gecko")
                .header("Accept", "*/*").header("Content-Type", "application/json;charset=UTF-8")
                .POST(HttpRequest.BodyPublishers.ofString(prepareRequest()))
                .build();
        HttpResponse<String> response = client.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
    private String prepareRequest() throws JsonProcessingException {
        Map<String,String> map=new HashMap<>();
        map.put("username","admin");
        map.put("password","admin456");
        map.put("code","48");
        map.put("uuid","5e7d7ef5b3144b7984588aca02ca33a2");
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(map);
        System.out.println(jsonStr);
        return jsonStr;
    }

Loading...

#2 Created at ... [Delete] [Delete and Lock User]
       <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.1</version>
        </dependency>

  • 1

Reply