调用第三方接口-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();
}
相关推荐
MarvinP5 分钟前
python基础:位置互换
开发语言·python·算法
Gauss松鼠会7 分钟前
GaussDB回调机制深度实践:从事件驱动到系统集成
开发语言·javascript·数据库·sql·gaussdb
独隅7 分钟前
Lua 函数使用的完整指南
开发语言·junit·lua·lua5.4
s_yellowfish12 分钟前
Maven笔记
java·笔记·maven
清霜之辰31 分钟前
详解 kotlin 相对 Java 特有的关键字及使用
android·java·kotlin
江沉晚呤时33 分钟前
深入解析策略模式在C#中的应用与实现
java·服务器·开发语言·前端·.netcore
居然是阿宋34 分钟前
Kotlin 中的 `reified` 关键字全解析:保留类型信息 + 优化高阶函数的双重魔法
android·开发语言·kotlin
Hamm35 分钟前
如何在TypeScript里使用类封装枚举来实现Java的枚举形参倒置
java·前端·typescript
mikey棒棒棒1 小时前
使用RabbitMQ实现异步秒杀
java·分布式·rabbitmq·mq
无情的搬砖机器1 小时前
idea 打不开terminal
java·ide·intellij-idea