java get请求

2023-12-14 22:34:05
package com.axatp.sfd.df;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetRequestExample1 {
    public static void main(String[] args) {
        String url1 = "https://baidu.com";
        test(url1);
    }

    public static void test(String url) {
        try {

            // 创建URL对象
//            String url = "https://baidu.com";
            URL obj = new URL(url);
            // 打开连接
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            // 设置请求方法为GET
            con.setRequestMethod("GET");
            // 获取响应代码
            int responseCode = con.getResponseCode();
//                    System.out.println("响应代码:" + responseCode);

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            System.out.println("id1: " + response);
            in.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



文章来源:https://blog.csdn.net/weixin_48616345/article/details/135005579
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。