本文主要介绍在 Java 编程中发送 HTTP 请求的两种常用方法:
- JDK 原生的 HttpURLConnection 发送 HTTP 请求
- Apache HhttpClient 发送 HTTP 请求
两种方法都可以发送 HTTP 请求,第一种是 Java 原生的,因此使用起来相对麻烦一些,第二种是通过第三方的包来实现,这个包是 Apache 旗下的专门用来发送 HTTP 请求的 HttpClient 包,是对 Java 原生的 HttpURLConnection 扩展,因此功能也更加强大,使用起来也相对简单一些,目前这种方式发送 HTTP 请求应用比较广泛,因此主要学习这种方式。
Apache HttpClient 官方文档见这里:http://hc.apache.org/httpcomponents-client-5.1.x/
Talk is cheap. Show me the code. 下面看具体使用代码示例。
1、JDK 原生的 HttpURLConnection 发送 HTTP 请求 GET/POST
基于 JDK 原生的 HttpURLConnection 类,简单封装了下 HTTP GET 和 POST 请求方法,重在学习使用。
package com.example.demo.common.utils;
/**
* Created by qianghaohao on 2021/5/16
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* @description: 使用 java 原生 HttpURLConnection 类发送 http 请求
* @author: qianghaohao
* @time: 2021/5/16
*/
public class HttpURLConnectionUtils {
public static String doGet(String httpUrl) {
HttpURLConnection connection = null;
InputStream inputStream = null;
BufferedReader bufferedReader = null;
String result = null;
try {
// 创建远程url连接对象
URL url = new URL(httpUrl);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
// 通过connection连接,获取输入流
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
// 封装输入流is,并指定字符集
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
// 存放数据
StringBuilder sb = new StringBuilder();
String temp;
while ((temp = bufferedReader.readLine()) != null) {
sb.append(temp);
sb.append(System.lineSeparator()); // 这里需要追加换行符,默认读取的流没有换行符,需要加上才能符合预期
}
result = sb.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e)