这里简单总结了,自定义请求的几种方式,话不多说直接上代码。
一、使用客户端工具
以下是个人总结的HttpUtils工具类,包含GET/POST两种方式
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpUtils {
/**
* 编码 ENCODING_UTF8
*/
public static final String ENCODING_UTF8 = "UTF-8";
/**
* 获取连接客户端工具
*/
private CloseableHttpClient httpClient;
/**
* 请求对象 包含 HttpPost/HttpGet
*/
private CloseableHttpResponse response;
/**
* 构建
*/
public HttpUtils() {
// 获取连接客户端工具
this.httpClient = HttpClients.createDefault();
}
/**
* 普通GET请求
* @param url 请求地址
* @param header 请求头
* @return 请求对象
* @throws URISyntaxException 路由 参数未编码,会造成请求解析失败
* @throws IOException IOException
*/
public CloseableHttpResponse get(String url, Map<String, String> header) throws URISyntaxException, IOException {
return get(url,header,null);
}
/**
* GET请求
* @param url 请求地址
* @param header 请求头
* @param param 请求携带参数
* @return 请求对象
* @throws URISyntaxException 路由 参数未编码,会造成请求解析失败
* @throws IOException IOException
*/
public CloseableHttpResponse get(String url, Map<String, String> header,Map<String,Serializable> param) throws URISyntaxException, IOException {
/*
* 由于GET请求的参数都是拼装在URL地址后方,所以我们要构建一个URL,带参数
*/
URIBuilder uriBuilder = new URIBuilder(url);
//参数处理
List<NameValuePair> list = responseParam(param);
uriBuilder.setParameters(list);
// 根据带参数的URI对象构建GET请求对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
/*
* 添加请求头信息
*/
// 浏览器表示
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
// 传输的类型
httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
// 自定义请求头
for (String head:header.keySet()){
httpGet.addHeader(head,header.get(head));
}
// 执行请求
return this.response = this.httpClient.execute(httpGet);
}
/**
* 带参数POST请求
* @param url 请求地址
* @param param 请求携带参数
* @return 请求对象
* @throws IOException IOException
*/
public CloseableHttpResponse postSendHttpRequestForm(String url, Map<String, Serializable> param) throws IOException {
return post(url,null,param);
}
/**
* 无参数POST请求
* @param url 请求地址
* @param header 请求头
* @return 请求对象
* @throws IOException IOException
*/
public CloseableHttpResponse post(String url, Map<String, String> header) throws IOException {
return post(url,header,null);
}
/**
* POST请求
* @param url 请求地址
* @param header 请求头
* @param param 请求携带参数
* @return 请求对象
* @throws IOException IOException
*/
public CloseableHttpResponse post(String url, Map<String, String> header,Map<String,Serializable> param) throws IOException {
//1.创建POST请求对象
HttpPost httpPost = new HttpPost(url);
//2.添加请求参数--创建请求参数, 处理参数
List<NameValuePair> list = responseParam(param);
//3.使用URL实体转换工具
UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, ENCODING_UTF8);
httpPost.setEntity(entityParam);
//4.添加请求头信息
// 浏览器表示
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
// 传输的类型
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
// 自定义请求头
if(null != header && !header.isEmpty()){
for (String head:header.keySet()){
httpPost.addHeader(head,header.get(head));
}
}
// 执行请求
return this.response = this.httpClient.execute(httpPost);
}
/**
* 通过链接获取 HttpEntity 结果JSON字符串
* @return 返回链接请求结果
* @throws IOException IOException
*/
public String getEntityStr() throws IOException {
// 获得响应的实体对象
HttpEntity entity = this.response.getEntity();
// 使用Apache提供的工具类进行转换成字符串
return EntityUtils.toString(entity, ENCODING_UTF8);
}
/**
* 通过链接获取 HttpEntity 结果JSON字符串
* @param response CloseableHttpResponse 连接
* @return 返回链接请求结果
* @throws IOException IOException
*/
public static String getEntityStr(CloseableHttpResponse response) throws IOException {
// 获得响应的实体对象
HttpEntity entity = response.getEntity();
// 使用Apache提供的工具类进行转换成字符串
return EntityUtils.toString(entity, ENCODING_UTF8);
}
/**
* 释放连接
*/
public void close(){
try {
if (null != response) {
response.close();
}
if(null != httpClient){
httpClient.close();
}
} catch (IOException e) {
System.err.println("释放连接出错");
e.printStackTrace();
}
}
public static String sendHttpRequestForm(String url,Map<String,Serializable> param) throws IOException{
// 获取连接客户端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
String entityStr = null;
CloseableHttpResponse response = null;
try {
// 创建POST请求对象
HttpPost httpPost = new HttpPost(url);
/*
* 添加请求参数
*/
// 创建请求参数
List<NameValuePair> list = responseParam(param);
// 使用URL实体转换工具
UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entityParam);
/*
* 添加请求头信息
*/
// 浏览器表示
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
// 传输的类型
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
// 执行请求
response = httpClient.execute(httpPost);
// 获得响应的实体对象
HttpEntity entity = response.getEntity();
// 使用Apache提供的工具类进行转换成字符串
entityStr = EntityUtils.toString(entity, "UTF-8");
// System.out.println(Arrays.toString(response.getAllHeaders()));
} catch (ClientProtocolException e) {
System.err.println("Http协议出现问题");
e.printStackTrace();
} catch (ParseException e) {
System.err.println("解析错误");
e.printStackTrace();
} finally {
// 释放连接
if (null != response) {
try {
response.close();
httpClient.close();
} catch (IOException e) {
System.err.println("释放连接出错");
e.printStackTrace();
}
}
}
// 打印响应内容
System.out.println(entityStr);
return entityStr;
}
//参数处理
public static List<NameValuePair> responseParam(Map<String,Serializable> param){
List<NameValuePair> list = new ArrayList<>();
if(null != param && !param.isEmpty()) {
/* 第一种添加参数的形式 */
/*uriBuilder.addParameter("name", "root");
uriBuilder.addParameter("password", "123456");*/
//循环遍历加入参数项
/*for (String key:param.keySet()){
uriBuilder.addParameter(key,param.get(key));
}*/
/* 第二种添加参数的形式 */
for (String key : param.keySet()) {
BasicNameValuePair param_dispose = new BasicNameValuePair(key, (String) param.get(key));
list.add(param_dispose);
}
}
return list;
}
}
运行测试:
public static void main(String[] args) {
String url = "http://www.baidu.com";
//请求工具对象
HttpUtils httpUtils = new HttpUtils();
//参数处理
Map<String, Serializable> params = new HashMap<>();
params.put("username", "username");
params.put("password", "123456");
String result = null;
try {
//请求获取结果
result = HttpUtils.getEntityStr(httpUtils.postSendHttpRequestForm(url,params));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("请求结果:"+result);
}
运行结果:
二、Java原生请求之流形式传输
以下是个人总结的HttpRequest 工具类,包含GET/POST两种方式
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpRequest {
private static Logger logger = LoggerFactory.getLogger(HttpRequest.class);
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
logger.info("urlNameString is:{}" + urlNameString);
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)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
logger.info(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.error("发送GET请求出现异常!",e);
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.error("发送 POST 请求出现异常!", e);
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}
运行测试:
public static void main(String[] args) {
//请求地址
String url = "http://www.baidu.com";
//请求参数
String requestparam = "";
System.out.println("【请求参数】:" + requestparam);
String remsg = "";
try{
//GET请求
remsg = HttpRequest.sendGet(url, requestparam);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("【请求结果】:"+remsg);
}
测试结果:
上边只给出了GET方式的测试代码及测试结果。POST方式虽没有给出测试示例,但已亲自测试使用。