如何使用HttpURLConnection发起一个GET请求呢?
下文笔者讲述使用HttpURLConnection发起GET请求的方法分享,如下所示
定义后台spring mvcGET接收页
实现思路: connection.setRequestMethod("GET"); 即可定义请求模式为GET例:
定义后台spring mvcGET接收页
@GetMapping("/list") public ResponseEntity list(@RequestParam(value = "name") String name) { return ResponseEntity.ok(users.stream().filter(i -> i.getName().equals(name)).collect(Collectors.toList())); } @Data @AllArgsConstructor public static class User { private String name; private int age; }HttpURLConnnection之GET请求页面
HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/list?name=java265").openConnection(); connection.setRequestMethod("GET"); //write header connection.setRequestProperty("Content-Type", "application/json"); //set timeout connection.setConnectTimeout(1000 * 5); connection.setReadTimeout(1000 * 10); //connect connection.connect(); int responseCode = connection.getResponseCode(); log.info("response code : {}", responseCode); // 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(); }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。