OkHTTP发送POST请求传送JSON数据
导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
</dependencies>
编写一个接口
@RequestMapping("/Json")
@ResponseBody
public JSONObject Json(@RequestBody JSONObject map) {
System.out.println(map);
map.put("success", true);
map.put("msg", UUID.randomUUID().toString());
HashMap<String, Object> stringObjectHashMap = new HashMap<>();
stringObjectHashMap.put("token", "asdascfr22rwf");
map.put("response", stringObjectHashMap);
return map;
}
编写OkHTTP的测试类发送请求这个接口
package com.example.demo.demos.web;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class HttpClentTest {
private final static String httpHeaderMediaType = "application/json;charset=utf-8";
private final static String httpHeaderContentType = "Content-Type";
private final static Logger logger = LoggerFactory.getLogger(HttpClentTest.class);
/**
* 设置默认30秒Http调用超时
*/
private final static OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.callTimeout(30, TimeUnit.SECONDS)
.build();
public static void main(String[] args) {
JSONObject jsonBody = new JSONObject();
jsonBody.put("appKey", UUID.randomUUID().toString());
jsonBody.put("appSecret", UUID.randomUUID().toString());
// 构建Request对象
RequestBody requestBody = RequestBody.create(MediaType.parse(httpHeaderMediaType), jsonBody.toJSONString());
Request request = new Request.Builder()
.addHeader(httpHeaderContentType, httpHeaderMediaType)
.addHeader("Accept", httpHeaderMediaType)
.post(requestBody)
.url("http://localhost:8282/Json")
.build();
Response signRsp = null;
try {
signRsp = client.newCall(request).execute();
if (signRsp.isSuccessful()) {
String body = signRsp.body().string();
JSONObject respBody = JSONObject.parseObject(body);
if (respBody.getBoolean("success")) {
System.out.println("===================================Token===================================");
System.out.println(respBody.getJSONObject("response").getString("token"));
} else {
logger.error("Http连接OpenapiAPi地址:openapiLoginUrl 失败,MSG= {}", respBody.getString("msg"));
}
}
} catch (IOException e) {
logger.error("Http连接OpenapiAPi地址:openapiLoginUrl 失败", e);
}
}
}
成功测试结果
===================================Token===================================
asdascfr22rwf
作者:隔壁老郭
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
Java入门到入坟
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!