在Java中发送HTTP请求是一种常见的操作,广泛应用于从网页抓取数据、与远程API通信、下载文件等场景。本文将详细介绍如何使用Java标准库中的HttpURLConnection类以及第三方库Apache HttpClient来发送HTTP请求,包括GET和POST请求,并涵盖进阶用法和最佳实践。

一、使用HttpURLConnection发送HTTP请求

HttpURLConnection是Java标准库提供的一个类,用于发送HTTP请求和接收HTTP响应。以下是使用HttpURLConnection发送GET和POST请求的基本步骤:

1. 发送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) throws Exception {

// 创建URL对象

URL url = new URL("http://www.example.com");

// 打开连接

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// 设置请求方法为GET

connection.setRequestMethod("GET");

// 获取响应码

int responseCode = connection.getResponseCode();

System.out.println("Response Code: " + responseCode);

// 读取响应

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String inputLine;

StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

}

in.close();

// 打印响应内容

System.out.println(response.toString());

// 关闭连接

connection.disconnect();

}

}

2. 发送POST请求

import java.io.DataOutputStream;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class HttpURLConnectionPostExample {

public static void main(String[] args) throws Exception {

// 创建URL对象

URL url = new URL("http://www.example.com");

// 打开连接

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// 设置请求方法为POST

connection.setRequestMethod("POST");

// 设置允许写入输出流

connection.setDoOutput(true);

// 发送请求参数

String urlParameters = "param1=value1¶m2=value2";

DataOutputStream wr = new DataOutputStream(connection.getOutputStream());

wr.writeBytes(urlParameters);

wr.flush();

wr.close();

// 获取响应码

int responseCode = connection.getResponseCode();

System.out.println("Response Code: " + responseCode);

// 读取响应

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String inputLine;

StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

}

in.close();

// 打印响应内容

System.out.println(response.toString());

// 关闭连接

connection.disconnect();

}

}

二、使用Apache HttpClient发送HTTP请求

Apache HttpClient是一个功能更强大的第三方库,提供了更多自定义选项,如连接管理、重试策略和缓存支持。

1. 发送GET请求

import org.apache.http.HttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

public class ApacheHttpClientGetExample {

public static void main(String[] args) throws Exception {

// 创建HttpClient对象

CloseableHttpClient httpClient = HttpClients.createDefault();

// 创建HttpGet对象

HttpGet httpGet = new HttpGet("http://www.example.com");

// 执行请求

HttpResponse response = httpClient.execute(httpGet);

// 获取响应实体

String responseBody = EntityUtils.toString(response.getEntity());

System.out.println(responseBody);

// 关闭HttpClient

httpClient.close();

}

}

2. 发送POST请求

”`java

import org.apache.http.HttpResponse;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

public class ApacheHttpClientPostExample {

public static void main(String[] args) throws Exception {

// 创建HttpClient对象

CloseableHttpClient httpClient = HttpClients.createDefault();

// 创建HttpPost对象

HttpPost httpPost = new HttpPost("http://www.example.com");

// 设置请求体

String json = "{\"param1\":\"value1\",\"param2\":\"value2\"}";

StringEntity entity = new StringEntity(json);

httpPost.setEntity(entity);

httpPost.setHeader("Content-type", "application/json");

// 执行请求

HttpResponse response = httpClient.execute(httpPost);

// 获取响应实体

String responseBody = EntityUtils.toString(response.getEntity());