Java HttpClient做http请求(form-data和json两种)
一、导入依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.13</version> </dependency>
二、方法
package cn.com.wind.utils; import cn.com.wind.exception.TranspondException; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; 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.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.nio.charset.StandardCharsets; /** * @Author qymeng * @Date 2021/10/25 * @Description 接口转发的工具类 */ @Slf4j public class TranspondUtils { /** * POST请求 * * @param json 请求的json体 * @param url 请求的url地址 */ public static String doPost(String json, String url) { HttpClient httpClient = new HttpClient(); // 设置http连接主机服务超时时间 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(35000); PostMethod postMethod = new PostMethod(url); // 设置post请求超时 postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000); // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反 postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true)); String result = null; try { RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8"); //请求头信息 postMethod.setRequestHeader("Content-Type", "application/json"); postMethod.setRequestEntity(entity); httpClient.executeMethod(postMethod); if (postMethod.getStatusCode() == HttpStatus.SC_OK) { // 获取响应输入流 InputStream inStream = postMethod.getResponseBodyAsStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8)); StringBuilder strber = new StringBuilder(); String line; while ((line = reader.readLine()) != null) strber.append(line).append("\n"); inStream.close(); result = strber.toString(); } else { throw new TranspondException("请求服务端失败,状态码不为200"); } } catch (IOException e) { throw new TranspondException("请求服务端失败,地址为:" + url); } catch (IllegalStateException e) { throw new TranspondException("url地址不正确,该地址为:" + url); } catch (Exception e) { throw new TranspondException("其他异常"); } return result; } public static String doPost(Object json, String url) { String s = JSON.toJSONString(json); return doPost(s, url); } /** * form-data 发送文件 * @param url * @param file * @return */ public static String httpPostFile(String url, MultipartFile file){ CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); String filename = file.getOriginalFilename(); builder.addBinaryBody("file", file.getBytes(), ContentType.MULTIPART_FORM_DATA, filename); // StringBody fileName = new StringBody("文件名称", ContentType.MULTIPART_FORM_DATA); // builder.addPart("fileName", fileName); HttpEntity entity = builder.build(); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); return EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (Exception e){ e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } /** * GET请求 * * @param url 请求的url地址 */ public static String doGet(String url) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; String result = ""; try { // 通过址默认配置创建一个httpClient实例 httpClient = HttpClients.createDefault(); // 创建httpGet远程连接实例 HttpGet httpGet = new HttpGet(url); // 设置配置请求参数 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间 .setConnectionRequestTimeout(35000)// 请求超时时间 .setSocketTimeout(60000)// 数据读取超时时间 .build(); // 为httpGet实例设置配置 httpGet.setConfig(requestConfig); // 执行get请求得到返回对象 response = httpClient.execute(httpGet); // 通过返回对象获取返回数据 HttpEntity entity = response.getEntity(); // 通过EntityUtils中的toString方法将结果转换为字符串 result = EntityUtils.toString(entity); // log.info("请求服务器成功"); } catch (IOException e) { throw new TranspondException("GET请求异常, URL为:" + url); } finally { // 关闭资源 if (null != response) { try { response.close(); } catch (IOException e) { throw new TranspondException("关闭CloseableHttpResponse时出现异常, URL为:" + url); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { throw new TranspondException("关闭CloseableHttpClient时出现异常, URL为:" + url); } } } return result; } public static JSONObject doGetJson(String url) { return JSONObject.parseObject(doGet(url)); } /** * 检测运行备用方案,检测http状态码 * @param json * @param url * @return */ public static boolean isRunning(String json, String url){ HttpClient httpClient = new HttpClient(); // 设置http连接主机服务超时时间 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(35000); PostMethod postMethod = new PostMethod(url); // 设置post请求超时 postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000); // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反 postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true)); try { RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8"); //请求头信息 postMethod.setRequestHeader("Content-Type", "application/json"); postMethod.setRequestEntity(entity); httpClient.executeMethod(postMethod); return postMethod.getStatusCode() == HttpStatus.SC_OK; } catch (IOException e) { throw new TranspondException("请求服务端失败,地址为:" + url); } catch (IllegalStateException e) { throw new TranspondException("url地址不正确,该地址为:" + url); } catch (Exception e) { throw new TranspondException("其他异常"); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】