使用原生java 发送http请求

643
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpUtil {
    
    /**
     * 发送 GET 请求
     * @param url 请求的 URL 地址
     * @return 请求得到的响应
     * @throws Exception
     */
    public static String sendGetRequest(String url) throws Exception {
        // 创建 URL 对象
        URL obj = new URL(url);
        // 打开 URL 的连接
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // 设置请求方法为 GET
        con.setRequestMethod("GET");
        // 设置请求头信息,模拟浏览器发送请求
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        // 获取响应码
        int responseCode = con.getResponseCode();
        System.out.println("Sending GET request to URL : " + url);
        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();
        // 返回响应内容
        return response.toString();
    }

    /**
     * 发送 POST 请求
     * @param url 请求的 URL 地址
     * @param parameters POST 请求的参数
     * @return 请求得到的响应
     * @throws Exception
     */
    public static String sendPostRequest(String url, Map<String, String> parameters) throws Exception {
        // 创建 URL 对象
        URL obj = new URL(url);
        // 打开 URL 的连接
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // 设置请求方法为 POST
        con.setRequestMethod("POST");
        // 设置请求头信息,模拟浏览器发送请求
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // 拼接 POST 请求的参数
        StringBuilder params = new StringBuilder();
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            params.append(entry.getKey());
            params.append("=");
            params.append(entry.getValue());
            params.append("&");
        }
        byte[] postData = params.toString().getBytes();

        // 向输出流写入 POST 请求的参数
        con.setDoOutput(true);
        con.getOutputStream().write(postData);

        // 获取响应码
        int responseCode = con.getResponseCode();
        System.out.println("Sending POST request to URL : " + url);
        System.out.println("Post parameters : " + params);
        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();
        // 返回响应内容
        return response.toString();
    }
}