Java的HttpRequest请求工具类

package com.xieh;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

/**
 * Http请求封装类,封装常用的Get,Post请求方法
 * 
 * @author 谢辉
 *
 */
public class HttpRequest {
	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url     发送请求的URL
	 * @param params  请求参数,
	 * @param headers 请求头参数
	 * @return result 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, Map<String, Object> params, Map<String, Object> headers) {
		String param = "";
		if (params != null) {
			int length = params.size();
			int count = 1;
			Set<Entry<String, Object>> entrySet = params.entrySet();
			for (Entry<String, Object> entry : entrySet) {
				if (count < length) {
					param += entry.getKey() + "=" + entry.getValue() + "&";
				} else {
					param += entry.getKey() + "=" + entry.getValue();
					break;
				}
				count++;
			}
		}
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			// connection.setRequestProperty("Accept-Charset", "UTF-8");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 添加用户设置的请求头
			if (headers != null) {
				Set<Entry<String, Object>> headerEntrySet = headers.entrySet();
				for (Entry<String, Object> entry : headerEntrySet) {
					connection.setRequestProperty(entry.getKey(), entry.getValue().toString());
				}
			}

			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			// for (String key : map.keySet()) {
			// System.out.println(key + "--->" + map.get(key));
			// }
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}

			byte[] bresult = result.getBytes();
			result = new String(bresult, "utf-8");
		} 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;
	}

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url      发送请求的URL
	 * @param params   请求参数
	 * @param headers  请求头参数
	 * @param encoding 设置响应信息的编码格式,如utf-8
	 * @return result 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, Map<String, Object> params, Map<String, Object> headers, String encoding) {
		String param = "";
		if (params != null) {
			int length = params.size();
			int count = 1;
			Set<Entry<String, Object>> entrySet = params.entrySet();
			for (Entry<String, Object> entry : entrySet) {
				if (count < length) {
					param += entry.getKey() + "=" + entry.getValue() + "&";
				} else {
					param += entry.getKey() + "=" + entry.getValue();
					break;
				}
				count++;
			}
		}
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 添加用户设置的请求头
			if (headers != null) {
				Set<Entry<String, Object>> headerEntrySet = headers.entrySet();
				for (Entry<String, Object> entry : headerEntrySet) {
					connection.setRequestProperty(entry.getKey(), entry.getValue().toString());
				}
			}
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			// for (String key : map.keySet()) {
			// System.out.println(key + "--->" + map.get(key));
			// }
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}

			byte[] bresult = result.getBytes();
			result = new String(bresult, encoding);
		} 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;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url   发送请求的 URL
	 * @param param 请求参数,请求参数应该是Json格式字符串的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String jsonData, Map<String, Object> headers) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection con = realUrl.openConnection();
			HttpURLConnection conn = (HttpURLConnection) con;
			// 设置通用的请求属性
			conn.setRequestMethod("POST"); // 设置Post请求
			conn.setConnectTimeout(5 * 1000);
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置内容类型
			// 添加用户设置的请求头
			if (headers != null) {
				Set<Entry<String, Object>> headerEntrySet = headers.entrySet();
				for (Entry<String, Object> entry : headerEntrySet) {
					conn.setRequestProperty(entry.getKey(), entry.getValue().toString());
				}
			}
			// conn.setRequestProperty("Content-Length",
			// String.valueOf(param.length())); //设置长度
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
			// 发送请求参数
			// out.print(param);
			out.write(jsonData);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			byte[] bresult = result.getBytes();
			result = new String(bresult, "utf-8");
		} 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;
	}

	public static String sendPost(String url, String jsonData, Map<String, Object> headers, String encoding,
			String authorization, String postmanToken) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection con = realUrl.openConnection();
			HttpURLConnection conn = (HttpURLConnection) con;
			// 设置通用的请求属性
			conn.setRequestMethod("POST"); // 设置Post请求
			conn.setConnectTimeout(5 * 1000);
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置内容类型
			conn.setRequestProperty("authorization", authorization);
			conn.setRequestProperty("postman-token", postmanToken);
			// 添加用户设置的请求头
			if (headers != null) {
				Set<Entry<String, Object>> headerEntrySet = headers.entrySet();
				for (Entry<String, Object> entry : headerEntrySet) {
					conn.setRequestProperty(entry.getKey(), entry.getValue().toString());
				}
			}
			// conn.setRequestProperty("Content-Length",
			// String.valueOf(param.length())); //设置长度
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), encoding));
			// 发送请求参数
			// out.print(param);
			out.write(jsonData);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			byte[] bresult = result.getBytes();
			result = new String(bresult, encoding);
		} 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;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url      发送请求的 URL
	 * @param jsonData 请求参数,请求参数应该是Json格式字符串的形式。
	 * @param encoding 设置响应信息的编码格式,如utf-8
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String jsonData, Map<String, Object> headers, String encoding) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection con = realUrl.openConnection();
			HttpURLConnection conn = (HttpURLConnection) con;
			// 设置通用的请求属性
			conn.setRequestMethod("POST"); // 设置Post请求
			conn.setConnectTimeout(5 * 1000);
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置内容类型
			// 添加用户设置的请求头
			if (headers != null) {
				Set<Entry<String, Object>> headerEntrySet = headers.entrySet();
				for (Entry<String, Object> entry : headerEntrySet) {
					conn.setRequestProperty(entry.getKey(), entry.getValue().toString());
				}
			}
			// conn.setRequestProperty("Content-Length",
			// String.valueOf(param.length())); //设置长度
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), encoding));
			// 发送请求参数
			// out.print(param);
			out.write(jsonData);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			byte[] bresult = result.getBytes();
			result = new String(bresult, encoding);
		} 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;
	}

	/**
	 * 上传媒体文件
	 * 
	 * @param url  上传媒体文件的微信公众平台接口地址
	 * @param file 要上传的媒体文件对象
	 * @return 返回上传的响应结果,详情参看微信公众平台开发者接口文档
	 */
	public static String uploadPost(String url, File file) {
		DataOutputStream dos = null;
		FileInputStream fis = null;
		DataInputStream dis = null;
		BufferedReader in = null;
		String result = "";
		String end = "\r\n";
		String twoHyphens = "--"; // 用于拼接
		String boundary = "*****"; // 用于拼接 可自定义
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection con = realUrl.openConnection();
			HttpURLConnection conn = (HttpURLConnection) con;
			// 设置通用的请求属性
			conn.setRequestMethod("POST"); // 设置Post请求
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(5 * 1000);
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // 设置内容类型

			// 获取URLConnection对象对应的输出流
			dos = new DataOutputStream(conn.getOutputStream());
			// 1、写入媒体头部分
			StringBuilder sb = new StringBuilder();
			sb.append(twoHyphens).append(boundary).append(end);
			sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"").append(end);
			sb.append("Content-Type:application/octet-stream").append(end).append(end);
			byte[] head = sb.toString().getBytes("utf-8");
			dos.write(head);

			// 2、写入媒体正文部分, 对文件进行传输
			fis = new FileInputStream(file);
			dis = new DataInputStream(fis);
			byte[] buffer = new byte[8192]; // 8K
			int count = 0;
			while ((count = dis.read(buffer)) != -1) {
				dos.write(buffer, 0, count);
			}

			// 3、写入媒体结尾部分。
			byte[] foot = (end + twoHyphens + boundary + twoHyphens + end).getBytes("utf-8");
			dos.write(foot);
			dos.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			byte[] bresult = result.getBytes();
			result = new String(bresult, "utf-8");
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (dos != null) {
					dos.close();
				}
				if (dis != null) {
					dis.close();
				}
				if (fis != null) {
					fis.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
}

 

Java中有多种HTTP请求工具类可供使用,其中一种是http-request。它基于URLConnection实现,不依赖于HttpClient。使用http-request发送GET请求示例如下: 1. 引入依赖: ``` <dependency> <groupId>com.github.kevinsawicki</groupId> <artifactId>http-request</artifactId> <version>5.6</version> </dependency> ``` 2. 发送GET请求获取响应报文: ```java String response = HttpRequest.get("http://www.baidu.com").body(); System.out.println("Response was: " + response); ``` 3. 发送GET请求获取响应码: ```java int code = HttpRequest.get("http://google.com").code(); ``` 除了http-request,还有其他一些常用的HTTP请求工具类,比如HttpUtil。使用HttpUtil发送GET请求的示例代码如下: ```java // 最简单的HTTP请求,自动判断编码 String result1 = HttpUtil.get("https://www.baidu.com"); // 自定义请求页面的编码 String result2 = HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8); // 传入http参数,参数会自动做URL编码,拼接在URL中 HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result3 = HttpUtil.get("https://www.baidu.com", paramMap); ``` 如果需要发送POST请求,可以使用HttpUtil的post方法,示例代码如下: ```java HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result = HttpUtil.post("https://www.baidu.com", paramMap); ``` 另外,如果需要文件上传,可以将参数中的键指定为"file",值设为文件对象即可,示例代码如下: ```java HashMap<String, Object> paramMap = new HashMap<>();paramMap.put("file", FileUtil.file("D:\\face.jpg")); String result = HttpUtil.post("https://www.baidu.com", paramMap); ``` 以上是一些常用的Java HTTP请求工具类,你可以根据具体需求选择适合的工具类来发送HTTP请求。请问您还有其他相关问题吗? 相关问题: 1. Java中还有哪些常用的HTTP请求工具类? 2. 如何处理HTTP请求的返回结果? 3. 如何设置HTTP请求的超时时间?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图图小淘气_real

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值