要强制使用UTF-8编码,可以使用以下代码示例:
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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;
import java.nio.charset.StandardCharsets;
public class ApacheHttpClientExample {
public static void main(String[] args) throws Exception {
// 创建 HttpClient 实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 GET 请求
HttpGet httpGet = new HttpGet("http://example.com");
// 设置请求头,强制使用 UTF-8 编码
httpGet.setHeader("Content-Type", "text/html; charset=UTF-8");
// 发送请求,并获取响应
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
// 将响应实体转换为字符串,使用 UTF-8 编码
String responseString = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println(responseString);
}
} finally {
// 关闭响应
response.close();
}
}
}
在上述示例中,我们创建了一个CloseableHttpClient
实例,并使用HttpClients.createDefault()
方法创建了一个默认的HttpClient。然后,我们创建了一个HttpGet实例,并设置了请求头,强制使用UTF-8编码。最后,我们使用httpClient.execute()
方法发送请求,并获取响应。
在获取响应实体后,我们使用EntityUtils.toString()
方法将响应实体转换为字符串,使用UTF-8编码。这样,我们就可以使用UTF-8编码处理响应数据了。