Java是一种广泛使用的编程语言,许多应用都需要与外部系统进行通信。在与外部系统通信时,使用HTTP请求是一种常见的方法。本篇文章将介绍如何封装Java HTTP请求工具类来支持多种请求方式。
- Get请求
Get请求是用于从服务器获取数据的一种请求方式。下面是一个使用Java原生URLConnection发送Get请求的示例:
public static String sendGet(String url) {
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
// 建立实际的连接
conn.connect();
// 获取所有响应头字段
Map<String, List<String>> map = conn.getHeaderFields();
// 遍历所有的响应头字段,获取cookie
for (String key : map.keySet()) {
if("Set-Cookie".equalsIgnoreCase(key)){
String cookie = map.get(key).get(0);
// 使用正则表达式提取cookie中的JSESSIONID
Pattern p = Pattern.compile("(?<=JSESSIONID=).*?(?=;)");
Matcher m = p.matcher(cookie);
if(m.find()){
String jsessionId = m.group();
// 将JSESSIONID存入全局变量,用于后续的请求中
session = jsessionId;
}
}
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
- Post表单提交请求
Post表单提交请求是一种用于向服务器提交数据的请求方式。下面是一个使用Java原生URLConnection发送Post表单提交请求的示例:
public static String sendPost(String url, String params) {
String result = "";
PrintWriter out = null;
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
conn.setRequestProperty("Cookie", "JSESSIONID=" + session);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
- Post表单文件提交请求
Post表单文件提交请求是一种用于上传文件到服务器的请求方式。下面是一个使用Java原生URLConnection发送Post表单文件提交请求的示例:
public static String sendPostFile(String url, String filePath) {
String result = "";
String boundary = "---------------------------" + System.currentTimeMillis();
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
conn.setRequestProperty("Cookie", "JSESSIONID=" + session);
conn.setRequestProperty("Content-Type", "multipart/form-data" + "; boundary=" + boundary);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 上传文件
File file = new File(filePath);
StringBuilder sb = new StringBuilder();
sb.append("--").append(boundary).append("\r\n");
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 输出流的缓冲区大小,即缓冲区大小
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
int len;
FileInputStream fis = new FileInputStream(file);
OutputStream os = conn.getOutputStream();
// 头信息
os.write(head);
// 文件内容
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
// 结束标记
byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes("utf-8");
os.write(end_data);
os.flush();
os.close();
fis.close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
return result;
}
- Post application/json 请求
Post application/json 请求是一种用于将JSON格式的数据提交到服务器的请求方式。下面是一个使用Java原生URLConnection发送Post application/json 请求的示例:
public static String sendPostJson(String url, String json) {
String result = "";
PrintWriter out = null;
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
conn.setRequestProperty("Cookie", "JSESSIONID=" + session);
conn.setRequestProperty("Content-Type", "application/json");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(json);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}}
- Webservice请求
Webservice请求是一种用于与Webservice服务进行通信的请求方式。下面是一个使用Java原生JAX-WS实现Webservice请求的示例:
public static String sendWebServiceRequest(String url, String methodName, Object... params) {
String result = "";
try {
// Step 1: 初始化WS服务客户端工厂对象
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
// Step 2: 设置WS服务发布的接口
factory.setServiceClass(IService.class);
// Step 3: 设置WS服务的请求地址
factory.setAddress(url);
// Step 4: 创建WS服务客户端
IService client = (IService) factory.create();
// Step 5: 调用WS服务的方法
result = client.invokeMethod(methodName, params);
} catch (Exception e) {
System.out.println("调用Web Service方法出现异常!" + e);
e.printStackTrace();
}
return result;
}
- 请求转发
请求转发是一种将请求在服务器端重新发送到另一个页面或servlet的方法。下面是一个使用Java原生HttpServletRequest实现请求转发的示例:
public static void forward(HttpServletRequest request, HttpServletResponse response, String path) {
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
try {
dispatcher.forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
总结
本篇文章介绍了如何封装Java HTTP请求工具类来支持多种请求方式,包括Get请求、Post表单提交请求、Post表单文件提交请求、Post application/json 请求、Webservice请求和请求转发。这些请求方式都是在实际开发中非常常见的,掌握这些技能可以帮助我们更加高效地与外部系统进行通信。