通过Java发送接口请求
前提须知:随笔引入fastjson对json解析进行简化
基础请求JDK版[非原生]
依赖:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
代码:
GET请求参数均以拼接url
//=========================获取连接=========================
//设置访问接口
URL url = new URL(locate);
//获取连接请求
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//=========================设置连接=========================
//设置请求方式
connection.setRequestMethod("POST");
//是否需要获取数据
connection.setDoInput(true);
//是否需要在请求体中设置内容
connection.setDoOutput(true);
//设置请求头
/*
1、setRequestProperty()设置
2、addRequestProperty()添加
*/
//connection.setRequestProperty("Accept","*/*");//设置接受类型
//connection.addRequestProperty("Connection","Keep-Alive");//默认持续连接
//connection.addRequestProperty("User-Agent","Mozilla/5.0 (Linux; X11)");//设置使用者
//connection.addRequestProperty("Charset","UTF-8");
connection.addRequestProperty("Content-Type","application/json");//json数据
//设置超时事件ms
connection.setConnectTimeout(5000);
//设置读写超时事件ms
connection.setReadTimeout(5000);
//是否使用缓存
connection.setUseCaches(false);
//=========================连接=========================
//连接的目的最终是对获取请求参数,所以在获取流的操作中会自带连接方法,无需手动连接
//connection.connect();
//=========================发送请求参数=========================
//获取网页的输出流
OutputStream outputStream = connection.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
//发送数据
Map map = new HashMap();
map.put("name","小李子");
map.put("id","1");
log.info("{}",JSONObject.toJSONString(map));
printWriter.write(JSONObject.toJSONString(map));
//关闭流
printWriter.flush();
printWriter.close();
//=========================获取请求参数=========================
//接口返回的参数已经在内存缓冲区了,直接从缓冲区获取数据即可
InputStream inputStream = connection.getInputStream();
//返回参数
StringBuffer stringBuffer = new StringBuffer();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes))!= -1){
stringBuffer.append(new String(bytes, Charset.forName("UTF-8")));
}
//关闭流
inputStream.close();
//关闭连接
connection.disconnect();
//stringBuffer为返回的json数据
return stringBuffer.toString();
基础请求Apache版
依赖:
<!-- 基础请求jar包 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<!-- 文件请求专用jar包 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
基础代码:
//=========================获取连接=========================
//创建客户端:用来创建web客户端的
CloseableHttpClient client = HttpClientBuilder.create().build();
//获取连接请求:用来设置接口的
HttpPost httpPost = new HttpPost(locate);
//设置响应模型:用来发送请求的
CloseableHttpResponse response = null;
//设置响应参数模型:专门获取响应参数
HttpEntity entity = null;
//=========================设置连接=========================
//对于GET方便请求的一些设置
//RequestConfig config = RequestConfig.custom()
// .setConnectTimeout(5000)//设置连接超时事件ms
// .setConnectionRequestTimeout(5000)//设置请求超时事件
// .setSocketTimeout(5000)//设置读写超时事件
// .setRedirectsEnabled(true)//是否支持重定向
// .build();//配置
//HttpGet httpGet = new HttpGet();
//httpGet.setConfig(config);
//设置请求头
httpPost.setHeader("Content-Type","application/json");
//设置请求体:需要使用自带的StringEntity对string封装
httpPost.setEntity(new StringEntity(JSONObject.toJSONString(new User()),"UTF-8"));
//=========================连接=========================
//获取响应模型
response = client.execute(httpPost);
//=========================获取请求参数=========================
//获取响应参数
entity = response.getEntity();
log.info("响应状态为:{}",response.getStatusLine());
log.info("响应内容:{}", EntityUtils.toString(entity));
//关流
client.close();
response.close();
return "with";
文件上传代码:
//=========================获取连接=========================
//创建客户端:用来创建web客户端的
CloseableHttpClient client = HttpClientBuilder.create().build();
//获取连接请求:用来设置接口的
HttpPost httpPost = new HttpPost(locate);
//设置响应模型:用来发送请求的
CloseableHttpResponse response = null;
//设置文件模型
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
//=========================设置文件=========================
//添加上传文件
//参数:接受参数名称,文件,<文件上传类型,文件名>
File file = new File("E:\\file\\one.txt");
multipartEntityBuilder.addBinaryBody("file",file
,ContentType.DEFAULT_BINARY, URLEncoder.encode(file.getName(),"UTF-8"));
//添加表单参数,contentType是防止服务端接受参数乱码的
//ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
//multipartEntityBuilder.addTextBody("aaa","aaa",contentType);
//重构设置参数
HttpEntity build = multipartEntityBuilder.build();
//注入参数
httpPost.setEntity(build);
//=========================连接=========================
response = client.execute(httpPost);
log.info("响应码:{}",response.getStatusLine());
文件下载代码:
//=========================获取连接=========================
//创建客户端:用来创建web客户端的
CloseableHttpClient client = HttpClientBuilder.create().build();
//获取连接请求:用来设置接口的
HttpGet httpGet = new HttpGet(locate);
//设置响应模型:用来发送请求的
CloseableHttpResponse response = null;
//设置响应参数模型:专门获取响应参数
HttpEntity entity = null;
//=========================连接=========================
//连接
response = client.execute(httpGet);
//=========================获取请求参数=========================
//获取参数
entity = response.getEntity();
log.info("响应状态为:{}",response.getStatusLine());
//获取流
byte[] data = EntityUtils.toByteArray(entity);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("E:\\file\\temp\\one.txt")));
bos.write(data);
bos.flush();
bos.close();
基础请求GitHub版[推荐]
自带Apache功能包,是对Apache在封装
依赖:
<dependency>
<groupId>com.arronlong</groupId>
<artifactId>httpclientutil</artifactId>
<version>1.0.4</version>
</dependency>
代码:
//=========================快速版=========================
String s2 = HttpClientUtil.get(HttpConfig.custom().url("http://localhost:8080/test2"));
log.info("无参 返回实体类{}",s2);
//=========================高级版=========================
//请求头设置
Header[] header = HttpHeader.custom()
.contentType("application/text/plain").build();
//连接配置
HttpClient client = HCB.custom()
.retry(5).build();
//参数
Map<String,Object> map = new HashMap<>();
map.put("key","value");
//最终配置
HttpConfig config = HttpConfig.custom()
.headers(header)//请求头
.url("")//请求
.map(map)//参数
.encoding("utf-8")//请求和编码格式
.client(client)//连接配置
//.out(new BufferedOutputStream(new FileOutputStream(new File("保存地址"))))//下载
//.files(new String[]{"上传文件本地地址"})//上传
;
//连接
HttpClientUtil.get(config);
HttpClientUtil.post(config);
HttpClientUtil.upload(config);//上传
HttpClientUtil.down(config);//下载
本文作者:Ch1ee
本文链接:https://www.cnblogs.com/daimourentop/p/16335182.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了