如何使用HttpURLConnection发起一个POST请求呢?
下文笔者讲述使用HttpURLConnection发起POST请求的方法分享,如下所示
定义后台spring mvcpost接收页
实现思路: 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(); }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。