1 简介
Java请求Http接口常用的方式有三种,如下表
序号 | 工具 | 描述 | 应用案例 |
---|---|---|---|
1 | URLConnection | Java原生,java.net.URLConnection | https://blog.csdn.net/Xin_101/article/details/122440247 |
2 | HttpURLConnection | Java原生,java.net.HttpURLConnection | https://blog.csdn.net/Xin_101/article/details/122449254 |
3 | httpclient | 第三方工具,org.apache.httpcomponents | https://blog.csdn.net/Xin_101/article/details/122449693 |
本章讲解:HttpURLConnection,该类继承URLConnection。
2 接口
3 测试
3.1 Code
package com.monkey.java_study.web;
import com.google.gson.Gson;
import com.monkey.java_study.common.constant.BooleanConstant;
import com.monkey.java_study.common.constant.WebConstant;
import com.monkey.java_study.common.entity.PageEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
* HttpUrlConnection请求接口测试样例.
*
* @author xindaqi
* @date 2022-01-11 20:07
*/
public class HttpUrlConnectionTest {
private static final Logger logger = LogManager.getLogger(HttpUrlConnectionTest.class);
/**
* GET请求.
*
* @param url 请求地址
* @return 响应数据
*/
public static String doGet(String url) {
HttpURLConnection urlConnection = null;
try {
// 新建URL对象
URL urlObject = new URL(url);
// 打开URL连接
urlConnection = (HttpURLConnection) urlObject.openConnection();
// 设置请求方法
urlConnection.setRequestMethod(WebConstant.GET_METHOD);
// 设置请求头内容类型和字符集类型
urlConnection.setRequestProperty(WebConstant.CONTENT_TYPE, WebConstant.APPLICATION_JSON);
// 不使用缓存
urlConnection.setUseCaches(BooleanConstant.FALSE);
// 设置连接超时时间,单位:毫秒
urlConnection.setConnectTimeout(2000);
// 设置读取数据超时时间,单位:毫秒
urlConnection.setReadTimeout(2000);
// 获取响应
return inputStreamProcess(urlConnection);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* POST请求.
*
* @param url 请求地址
* @param params 请求参数:JSON字符串
* @return 响应数据
*/
public static String doPost(String url, String params) {
HttpURLConnection urlConnection = null;
try {
// 新建URL对象
URL urlObject = new URL(url);
// 打开URL连接
urlConnection = (HttpURLConnection) urlObject.openConnection();
// 设置请求方法
urlConnection.setRequestMethod(WebConstant.POST_METHOD);
// 设置请求头内容类型和字符集类型
urlConnection.setRequestProperty(WebConstant.CONTENT_TYPE, WebConstant.APPLICATION_JSON);
urlConnection.setRequestProperty("accept", "*/*");
urlConnection.setRequestProperty("connection", "Keep-Alive");
urlConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 允许写出
urlConnection.setDoOutput(BooleanConstant.TRUE);
// 允许写入
urlConnection.setDoInput(BooleanConstant.TRUE);
// 不使用缓存
urlConnection.setUseCaches(BooleanConstant.FALSE);
// 设置连接超时时间,单位:毫秒
urlConnection.setConnectTimeout(2000);
// 设置读取数据超时时间,单位:毫秒
urlConnection.setReadTimeout(2000);
return responseProcess(urlConnection, params);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* 获取响应参数.
*
* @param urlConnection Http连接对象
* @param params 请求参数
* @return 响应数据
*/
public static String responseProcess(URLConnection urlConnection, String params) {
try (PrintWriter printWriter = new PrintWriter(urlConnection.getOutputStream())) {
// 发送请求参数
printWriter.print(params);
// 刷新输出流
printWriter.flush();
return inputStreamProcess(urlConnection);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* 获取响应数据.
*
* @param urlConnection Http连接对象
* @return 响应数据
*/
public static String inputStreamProcess(URLConnection urlConnection) {
try (InputStream inputStream = urlConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
StringBuilder response = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
return response.toString();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static void main(String[] args) {
// GET:请求
String getUrl = "http://localhost:9121/api/v1/mongodb/read?userId=0x001";
String getResponse = doGet(getUrl);
logger.info(">>>>>>>>>Get response:{}", getResponse);
// POST:请求
String postUrl = "http://localhost:9121/api/v1/mongodb/page";
// 入参实体
PageEntity pageEntity = new PageEntity(1, 2);
Gson gson = new Gson();
// 实体转JSON字符串
String jsonString = gson.toJson(pageEntity);
String postResponse = doPost(postUrl, jsonString);
logger.info(">>>>>>>>>>Post response:{}", postResponse);
}
}
3.2 测试结果
4 小结
- HttpURLConnection发送POST请求:参数使用PrintWriter;
- POST参数传入时转换为JSON字符串;
- 可配置请求方法、连接超时时间、读取超时时间。