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

书欣 Java经验 发布时间:2022-10-12 23:38:18 阅读数:19246 1 HttpURLConnection
下文笔者讲述使用HttpURLConnection发起GET请求的方法分享,如下所示
实现思路:
    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();
}
版权声明

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

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

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

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

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者