java 常规http请求工具类

package com.ruoyi.utils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;

/**
 *
 * @Description: Http工具
 * @author: k
 * @date: 2022年8月22日 上午9:26:54
 */
public class HttpUtil {
	private static final int CONNECT_TIMEOUT=5000;
	private static final int SOCKET_TIMEOUT=10000;
	static RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
	public static String doGet(String url, Map<String, String> requestParam, Map<String, String> headerParam) {
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		String param = "";
		if (requestParam != null) {
			StringBuffer buffer = new StringBuffer();
			buffer.append("?");
			requestParam.forEach((k, v) -> {
				buffer.append(k + "=" + v + "&");
			});
			param = buffer.toString().substring(0, buffer.length() - 1);
		}
		// 创建Get请求
		HttpGet httpGet = new HttpGet(url + param);
		httpGet.setConfig(requestConfig);
		if (headerParam != null) {
			headerParam.forEach((k, v) -> {
				httpGet.setHeader(k, v);
			});
		}
		String result = null;
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Get请求
			response = httpClient.execute(httpGet);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			if (responseEntity != null) {
				result = EntityUtils.toString(responseEntity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static String doPostJson(String url, JSONObject requestParam, Map<String, String> headerParam) {
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		// 创建Post请求
		HttpPost httpPost = new HttpPost(url);
//		httpPost.setConfig(requestConfig);
		StringEntity entity = new StringEntity(requestParam.toJSONString(), "UTF-8");

		// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
		httpPost.setEntity(entity);
		httpPost.setHeader("Content-Type", "application/json;charset=utf8");

		String result = null;
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			if (headerParam != null) {
				headerParam.forEach((k, v) -> {
					httpPost.setHeader(k, v);
				});
			}
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			//			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				result = EntityUtils.toString(responseEntity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return result;
	}

	public static String doPostXWWWFormUrlEncoded(String url, Map<String, String> requestParam, Map<String, String> headerParam) {
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		// 创建Post请求
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(requestConfig);
		//装填参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if (requestParam != null) {
			requestParam.forEach((k, v) -> {
				nvps.add(new BasicNameValuePair(k, v));
			});
		}

		httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

		String result = null;
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			if (headerParam != null) {
				headerParam.forEach((k, v) -> {
					httpPost.setHeader(k, v);
				});
			}
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			//			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				result = EntityUtils.toString(responseEntity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return result;
	}

	public static String doPostFormData(String url, String fileName, Map<String, String> requestParam, Map<String, String> headerParam) {
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		// 创建Post请求
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(requestConfig);
		CloseableHttpResponse response = null;
		String result = null;
		try {
			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
			// 第一个文件(多个文件的话,使用同一个key就行,后端用数组或集合进行接收即可)
			String filesKey = "file";
			File file = new File(fileName);
			multipartEntityBuilder.addBinaryBody(filesKey, file);
			// 防止服务端收到的文件名乱码。 我们这里可以先将文件名URLEncode,然后服务端拿到文件名时在URLDecode。就能避免乱码问题。
			// 文件名其实是放在请求头的Content-Disposition里面进行传输的,如其值为form-data; name="files"; filename="头像.jpg"
			//		      multipartEntityBuilder.addBinaryBody(filesKey, file2, ContentType.DEFAULT_BINARY, URLEncoder.encode(file2.getName(), "utf-8"));
			// 其它参数(注:自定义contentType,设置UTF-8是为了防止服务端拿到的参数出现乱码)
			if (requestParam != null) {
				ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
				requestParam.forEach((k, v) -> {
					multipartEntityBuilder.addTextBody(k, v, contentType);
				});
			}

			HttpEntity httpEntity = multipartEntityBuilder.build();
			httpPost.setEntity(httpEntity);

			response = httpClient.execute(httpPost);
			HttpEntity responseEntity = response.getEntity();
			if (responseEntity != null) {
				// 主动设置编码,来防止响应乱码
				result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的 Java 发送 HTTP 请求工具类: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpUtil { // 发送 GET 请求 public static String sendGet(String url) { StringBuilder result = new StringBuilder(); try { URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result.append(line); } in.close(); } catch (Exception e) { e.printStackTrace(); } return result.toString(); } // 发送 POST 请求 public static String sendPost(String url, String param) { StringBuilder result = new StringBuilder(); try { URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setDoOutput(true); conn.getOutputStream().write(param.getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result.append(line); } in.close(); } catch (Exception e) { e.printStackTrace(); } return result.toString(); } } ``` 使用方法示例: ```java String url = "http://www.example.com/api"; String result = HttpUtil.sendGet(url); System.out.println(result); String param = "name=John&age=25"; result = HttpUtil.sendPost(url, param); System.out.println(result); ``` 注:以上代码仅供参考,实际使用时需要根据具体需求进行修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值