如何使用HttpURLConnection发起一个POST请求呢?

书欣 Java经验 发布时间:2022-10-12 23:33:41 阅读数:6679 1 HttpURLConnection
下文笔者讲述使用HttpURLConnection发起POST请求的方法分享,如下所示
实现思路:
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
	即可定义请求模式为POST
例:
定义后台spring mvcpost接收页
@PostMapping("/demo")
    public ResponseEntity create(@RequestBody User user) {
        users.add(user);
        return ResponseEntity.ok(user);
    }
 @Data
    @AllArgsConstructor
    public static class User {
        private String name;
        private int age;
    }
HttpURLConnnection之POST请求页面
HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/demo").openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);

//write header
connection.setRequestProperty("Content-Type", "application/json");

//write body
try (PrintWriter writer = new PrintWriter(connection.getOutputStream())) {
    Map<String, String> user = new HashMap<>();
    user.put("name", "java265.com");
    user.put("age", "22");
    writer.write(JSONObject.toJSONString(user));
    writer.flush();
}

//read response
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} finally {
    connection.disconnect();
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202210/16655888794624.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者