调用第三方接口-OkHttpClient

请求方式

POST

单个新增

例如后端接口接收参数为 User user

使用OkHttpClient发送post请求

java 复制代码
//封装body信息
JsonObject jsonObject = new JsonObject();
jsonObject.put("userName","张三");
jsonObject.put("city","北京");
String url = "请求接口url"
OkHttpClient okHttpClient = new OkHttpClient();
MediaType json = MediaType.parse("application/json;charset=utf-8);
RequestBody body = RequestBody.create(json,JSON.toJsonString(jsonObject));
Request request = new Request.Builder()
		.url(url)
		.addHeader("Authorization","bearer aga0PU8AVdsas1f9KJfnb")
		.post(body)
		.build();
try{
	Response response = okHttpClient.newCall(request).execute();
	if(response.isSucessful() && response.body() != null){
		System.out.println(response.body.string());
	}
} catch (Exception e) {
	e.printStackTrace();
}

GET

使用OkHttpClient发送GET请求,如查询列表

服务端接口http://12.131.23.1/user/list

参数(UserReqDto userReqDto)

java 复制代码
String url = "http://12.131.23.1/user/list?userName=张三"

OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
		.url(url)
		.addHeader("Authorization","bearer aga0PU8AVdsas1f9KJfnb")
		.get()
		.build();
try{
	Response response = okHttpClient.newCall(request).execute();
	if(response.isSucessful() && response.body() != null){
		System.out.println(response.body.string());
	}
} catch (Exception e) {
	e.printStackTrace();
}
相关推荐
froginwe116 分钟前
R 基础运算
开发语言
醉城夜风~7 分钟前
[数据结构]堆详解
开发语言·数据结构
用户611881615196226 分钟前
Java基础面试题
java
17´33 分钟前
Qt从入门到入土(八) -打包Qt程序
开发语言·c++·qt
AI+程序员在路上35 分钟前
QT显示网页控件QAxWidget、QWebEngineView及区别
开发语言·qt
南玖yy40 分钟前
C语言柔性数组深度解析:动态内存管理的艺术
c语言·开发语言·柔性数组
2301_764441331 小时前
python实现的生态模拟系统
开发语言·python·pygame
DavidSoCool1 小时前
Elasticsearch Java API Client [8.17] 使用
java·大数据·elasticsearch
无世世1 小时前
【Java从入门到起飞】面向对象编程(高级)
java·开发语言
q567315231 小时前
使用CPR库编写的爬虫程序
开发语言·爬虫·golang·音视频