Java中可以使用Java标准库中的HttpURLConnection类或第三方库如Apache HttpComponents来发送HTTP请求。

下面是使用HttpURLConnection发送GET请求的示例代码:

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

public class HttpUrlConnectionExample {

    public static void main(String[] args) {
        try {
            String url = "https://jsonplaceholder.typicode.com/posts/1";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            int responseCode = con.getResponseCode();
            System.out.println("Response Code : " + responseCode);
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

需要注意的是,如果需要发送POST请求或其他类型的请求,需要设置请求方法和请求体,具体可以参考HttpURLConnection类的API文档。

用java发送http请求

原文地址: https://www.cveoy.top/t/topic/4mg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录