HttpURLConnection 怎么使用?

HttpURLConnection 怎么使用?

面是一个完整的使用 HttpURLConnection 进行 POST 请求的案例,可以直接抄作业:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostExample {
    private final String USER_AGENT = "Mozilla/5.0";
    public static void main(String[] args) throws Exception {
        HttpPostExample http = new HttpPostExample();
        // 发送 POST 请求
        http.sendPost();
    private void sendPost() throws Exception {
        // 请求的 URL
        String url = "http://example.com/api/login";
        // 创建 HttpURLConnection 对象
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // 设置请求方法为 POST
        con.setRequestMethod("POST");
        // 设置请求头信息
        con.setRequestProperty("User-Agent", USER_AGENT); // 设置请求用户代理
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // 设置请求语言
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置请求正文类型
        // 设置请求正文
        String username = "test";
        String password = "123456";
        String urlParameters = "username=" + username + "&password=" + password; // 请求参数
        con.setDoOutput(true); // 设置可输出数据
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters); // 输出请求参数
        wr.flush(); // 刷新输出流
        wr.close();
        // 发送请求
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        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();