java实现利用httpclient访问接口
HTTP协议时Internet上使用的很多也很重要的一个协议,越来越多的java应用程序需要通过HTTP协议来访问网络资源。
HTTPClient提供的主要功能:
1、实现了所有HTTP的方法(GET、POST、等PUT、HEAD);
2、支持自动转向;
3、支持HTTPS协议;
4、支持代理服务器等。
使用HttpClient需要以下6个步骤:
- 创建HttpClient的实例
- 创建某种连接方法的实例,GetMethod/PostMethod。在 GetMethod/PostMethod的构造函数中传入待连接的地址
- 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
- 读response
- 释放连接。无论执行方法是否成功,都必须释放连接
- 对得到后的内容进行处理
java实现利用httpclient访问接口
利用枚举先new 四种访问方式
package util; import org.apache.http.client.methods.*; /** * @author jreffchen */ public enum HttpRequestMethedEnum { // HttpGet请求 HttpGet { @Override public HttpRequestBase createRequest(String url) { return new HttpGet(url); } }, // HttpPost 请求 HttpPost { @Override public HttpRequestBase createRequest(String url) { return new HttpPost(url); } }, // HttpPut 请求 HttpPut { @Override public HttpRequestBase createRequest(String url) { return new HttpPut(url); } }, // HttpDelete 请求 HttpDelete { @Override public HttpRequestBase createRequest(String url) { return new HttpDelete(url); } }; public HttpRequestBase createRequest(String url) { return null; } }写一个HttpClientUtil通用类
package util; import com.alibaba.fastjson.JSON; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.*; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.Map; /** * @author jreffchen */ public class HttpClientUtil { /** * httpclient使用步骤 * 1、创建一个HttpClient对象; * 2、创建一个Http请求对象并设置请求的URL,比如GET请求就创建一个HttpGet对象,POST请求就创建一个HttpPost对象; * 3、如果需要可以设置请求对象的请求头参数,也可以往请求对象中添加请求参数; * 4、调用HttpClient对象的execute方法执行请求; * 5、获取请求响应对象和响应Entity; * 6、从响应对象中获取响应状态,从响应Entity中获取响应内容; * 7、关闭响应对象; * 8、关闭HttpClient. */ private static RequestConfig requestConfig = RequestConfig.custom() //从连接池中获取连接的超时时间 // 要用连接时尝试从连接池中获取,若是在等待了一定的时间后还没有获取到可用连接(比如连接池中没有空闲连接了)则会抛出获取连接超时异常。 .setConnectionRequestTimeout(15000) //与服务器连接超时时间:httpclient会创建一个异步线程用以创建socket连接,此处设置该socket的连接超时时间 //连接目标url的连接超时时间,即客服端发送请求到与目标url建立起连接的最大时间。超时时间3000ms过后,系统报出异常 .setConnectTimeout(15000) //socket读数据超时时间:从服务器获取响应数据的超时时间 //连接上一个url后,获取response的返回等待时间 ,即在与目标url建立连接后,等待放回response的最大时间,在规定时间内没有返回响应的话就抛出SocketTimeout。 .setSocketTimeout(15000) .build(); /** * 发送http请求 * * @param requestMethod 请求方式(HttpGet、HttpPost、HttpPut、HttpDelete) * @param url 请求路径 * @param params post请求参数 * @param header 请求头 * @return 响应文本 */ public static String sendHttp(HttpRequestMethedEnum requestMethod, String url, Map<String, Object> params, Map<String, String> header) { //1、创建一个HttpClient对象; CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = null; String responseContent = null; //2、创建一个Http请求对象并设置请求的URL,比如GET请求就创建一个HttpGet对象,POST请求就创建一个HttpPost对象; HttpRequestBase request = requestMethod.createRequest(url); request.setConfig(requestConfig); //3、如果需要可以设置请求对象的请求头参数,也可以往请求对象中添加请求参数; if (header != null) { for (Map.Entry<String, String> entry : header.entrySet()) { request.setHeader(entry.getKey(), entry.getValue()); } } // 往对象中添加相关参数 try { if (params != null) { ((HttpEntityEnclosingRequest) request).setEntity( new StringEntity(JSON.toJSONString(params), ContentType.create("application/json", "UTF-8"))); } //4、调用HttpClient对象的execute方法执行请求; httpResponse = httpClient.execute(request); //5、获取请求响应对象和响应Entity; HttpEntity httpEntity = httpResponse.getEntity(); //6、从响应对象中获取响应状态,从响应Entity中获取响应内容; if (httpEntity != null) { responseContent = EntityUtils.toString(httpEntity, "UTF-8"); } } catch (IOException e) { e.printStackTrace(); } finally { try { //7、关闭响应对象; if (httpResponse != null) { httpResponse.close(); } //8、关闭HttpClient. if (httpClient != null) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return responseContent; } } 最后,单元测试 Get请求: /** * 获取流程定义列表 * @throws UnsupportedEncodingException 转码异常 */ @Test public void getProcessDefinitionList() throws UnsupportedEncodingException { String url = "http://127.0.0.1:8080/activiti-rest/service/repository/process-definitions"; // 存储相关的header值
Map<String,String> header = new HashMap<String, String>(); //username:password--->访问的用户名,密码,并使用base64进行加密,将加密的字节信息转化为string类型,encoding--->token String encoding = DatatypeConverter.printBase64Binary("kermit:kermit".getBytes("UTF-8")); header.put("Authorization", "Basic " + encoding); String response = HttpClientUtil.sendHttp(HttpRequestMethedEnum.HttpGet,url, null,header); System.out.println(JSON.toJSONString(JSONObject.parseObject(response),true)); }Post请求:
/** * 历史流程实例列表(以post方式,推荐) * @throws UnsupportedEncodingException 转码异常 */ @Test public void postHistoryProcessInstancesList() throws UnsupportedEncodingException { String url = "http://127.0.0.1:8080/activiti-rest/service/query/historic-process-instances"; // 存储相关的header值 Map<String,String> header = new HashMap<String, String>(); //username:password--->访问的用户名,密码,并使用base64进行加密,将加密的字节信息转化为string类型,encoding--->token String encoding = DatatypeConverter.printBase64Binary("kermit:kermit".getBytes("UTF-8")); header.put("Authorization", "Basic " + encoding); // 相关请求参数 Map<String,Object> params = new HashMap<String, Object>(); params.put("processDefinitionKey", "process"); String response = HttpClientUtil.sendHttp(HttpRequestMethedEnum.HttpPost,url,params, header); System.out.println(JSON.toJSONString(JSONObject.parseObject(response),true)); }Put请求
/** * 更新任务 * * @throws UnsupportedEncodingException 转码异常 */ @Test public void putProcessRuntimeTask() throws UnsupportedEncodingException { String url = "http://127.0.0.1:8080/activiti-rest/service/runtime/tasks/50019"; // 存储相关的header值 Map<String, String> header = new HashMap<String, String>(); //username:password--->访问的用户名,密码,并使用base64进行加密,将加密的字节信息转化为string类型,encoding--->token String encoding = DatatypeConverter.printBase64Binary("kermit:kermit".getBytes("UTF-8")); header.put("Authorization", "Basic " + encoding); // 存储相关的params值 Map<String, Object> params = new HashMap<String, Object>(); params.put("assignee", "zhangsan"); String response = HttpClientUtil.sendHttp(HttpRequestMethedEnum.HttpPut, url, params, header); System.out.println(JSON.toJSONString(JSONObject.parseObject(response), true)); }Delete请求/** * 删除任务的一个IdentityLink * * @throws UnsupportedEncodingException 转码异常 */ @Test public void deleteProcessRuntimeIdentityLink() throws UnsupportedEncodingException { String url = "http://127.0.0.1:8080/activiti-rest/service/runtime/tasks/50014/identitylinks/users/wangwu/candidate"; // 存储相关的header值 Map<String, String> header = new HashMap<String, String>(); //username:password--->访问的用户名,密码,并使用base64进行加密,将加密的字节信息转化为string类型,encoding--->token String encoding = DatatypeConverter.printBase64Binary("kermit:kermit".getBytes("UTF-8")); header.put("Authorization", "Basic " + encoding); String response = HttpClientUtil.sendHttp(HttpRequestMethedEnum.HttpDelete, url, null, header); System.out.println(JSON.toJSONString(JSONObject.parseObject(response), true)); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程