100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > http请求发送工具类

http请求发送工具类

时间:2022-05-07 00:02:42

相关推荐

http请求发送工具类

直接引用的公司的工具类

依赖

<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.3</version></dependency>

代码

package mon.utils;import cn.hutool.core.io.IoUtil;import com.alibaba.fastjson.JSON;import mons.httpclient.*;import mons.httpclient.methods.GetMethod;import mons.httpclient.params.HttpMethodParams;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.ponent;import org.springframework.util.StringUtils;import java.io.IOException;import java.util.Map;@Componentpublic class HttpComponet {private static final Logger logger = LoggerFactory.getLogger(HttpComponet.class);private static final String logTemplate = "请求方法:[{}], 业务:[{}], 事件:[{}]";private static final String UTF8 = "UTF-8";private static final int MAX_TIMEOUT = 10 * 1000;private static RequestConfig requestConfig;static {RequestConfig.Builder config = RequestConfig.custom();config.setConnectionRequestTimeout(MAX_TIMEOUT);config.setConnectTimeout(MAX_TIMEOUT);config.setSocketTimeout(MAX_TIMEOUT);requestConfig = config.build();}/**httpClient的get请求方式2* @return* @throws Exception*/public static String doGet(String url, String charset)throws Exception {/** 使用 GetMethod 来访问一个 URL 对应的网页,实现步骤: 1:生成一个 HttpClinet 对象并设置相应的参数。* 2:生成一个 GetMethod 对象并设置响应的参数。 3:用 HttpClinet 生成的对象来执行 GetMethod 生成的Get* 方法。 4:处理响应状态码。 5:若响应正常,处理 HTTP 响应内容。 6:释放连接。*//* 1 生成 HttpClinet 对象并设置参数 */HttpClient httpClient = new HttpClient();// 设置 Http 连接超时为5秒httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);/* 2 生成 GetMethod 对象并设置参数 */GetMethod getMethod = new GetMethod(url);// 设置 get 请求超时为 5 秒getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);// 设置请求重试处理,用的是默认的重试处理:请求三次getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());String response = "";/* 3 执行 HTTP GET 请求 */try {int statusCode = httpClient.executeMethod(getMethod);/* 4 判断访问的状态码 */if (statusCode != HttpStatus.SC_OK) {System.err.println("请求出错: "+ getMethod.getStatusLine());}/* 5 处理 HTTP 响应内容 */// HTTP响应头部信息,这里简单打印Header[] headers = getMethod.getResponseHeaders();for (Header h : headers)System.out.println(h.getName() + "------------ " + h.getValue());// 读取 HTTP 响应内容,这里简单打印网页内容byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组response = new String(responseBody, charset);// 读取为 InputStream,在网页内容数据量大时候推荐使用// InputStream response = getMethod.getResponseBodyAsStream();} catch (HttpException e) {// 发生致命的异常,可能是协议不对或者返回的内容有问题System.out.println("请检查输入的URL!");e.printStackTrace();} catch (IOException e) {// 发生网络异常System.out.println("发生网络异常!");e.printStackTrace();} finally {/* 6 .释放连接 */getMethod.releaseConnection();}return response;}/*** post请求* @param url* @return*/public static String doPost(String url, String data){DefaultHttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(url);String result = null;try {StringEntity s = new StringEntity(data);s.setContentEncoding("UTF-8");s.setContentType("application/json");//发送json数据需要设置contentTypepost.setEntity(s);HttpResponse res = client.execute(post);if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){result = EntityUtils.toString(res.getEntity());}else {logger.error("虚拟号请求失败,异常信息:" +JSON.toJSONString(res)+"--------请求参数:"+data+"----------请求地址:"+url);}} catch (Exception e) {throw new RuntimeException(e);}return result;}public static void post(String methodName, String ipcType, String url, Map<String, String> header, HttpEntity entity, String param, HttpCallback callback) {CloseableHttpClient httpClient = null;try {logger.info(logTemplate, methodName, ipcType, "请求地址: " + url);HttpPost httpPost = new HttpPost(url);if (null != header) {for (Map.Entry<String, String> entry : header.entrySet()) {httpPost.addHeader(entry.getKey(), entry.getValue());logger.info(logTemplate, methodName, ipcType, "请求头: " + entry.getKey() + "=" + entry.getValue());}}httpPost.setConfig(requestConfig);httpPost.setEntity(entity);logger.info(logTemplate, methodName, ipcType, "请求参数: " + param);httpClient = HttpClients.createDefault();httpClient.execute(httpPost, response -> {int statusCode = response.getStatusLine().getStatusCode();logger.info(logTemplate, methodName, ipcType, "响应状态: " + statusCode);String result;if (null != callback) {result = callback.handler(response);} else {result = EntityUtils.toString(response.getEntity());}if (!StringUtils.isEmpty(result)) {logger.info(logTemplate, methodName, ipcType, "响应内容: " + result);}return null;});} catch (Exception e) {logger.error(logTemplate, methodName, ipcType, "请求异常", e);} finally {IoUtil.close(httpClient);}}public interface HttpCallback {String handler(HttpResponse resp);}public static void main(String[] args) throws Exception {System.out.println( doGet("https://wsjc.oss-cn-/%E9%82%AE%E4%BB%B6%E6%A8%A1%E6%9D%BF/%E4%B8%87%E9%A1%BA%E5%8F%AB%E8%BD%A6-%E7%94%B5%E5%AD%90%E5%8F%91%E7%A5%A8.pdf","UTF-8"));}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。