最近有一个需求,需要在SpringBoot项目中进行Http请求,获取数据,然后解析数据存储到mysql数据库表中。
根据大佬的提示,用 Unirest 进行Http请求十分方便
具体流程参考官网:
- maven项目中引入依赖
<!-- Pull in as a traditional dependency -->
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.11.09</version>
</dependency>
<!-- OR as a snazzy new standalone jar with shaded dependencies -->
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.11.09</version>
<classifier>standalone</classifier>
</dependency>
- 构建Post请求实体
String group = "dxxx";
String startTime = DateTimeUtils.dateStart(DateTimeUtils.getCurrentTimeStr(DateTimeUtils.DATE_FORMAT_WITH_BAR));
String endTime = DateTimeUtils.getCurrentTimeStr(DateTimeUtils.DATE_FORMAT_FULL);
//请求的主体
JSONObject jsonObject = new JSONObject();
jsonObject.put("group", group)
.put("startTime", startTime)
.put("endTime", endTime);
- Unirest 的Post请求
HttpResponse<JsonNode> response = Unirest.post("http://**.**.com/***/***")
.header("accept", "application/json").header("content-type", "application/json")
.body(jsonObject)
.asJson();
-
至此,如果返回的请求响应表示你的“开始时间不能为空”的错误。一定要注意检查JSONObject 是来自 ong.unirest.json.JSONObject,
如果你要用 org.json.JSONObject, 那么,上面的post请求要用 .body(jsonObject.toString()) -
经验教训:
一定要多试试同名参数中的不同方法,或者进入Unirest 封装的body 方法中debug,才能发现原来封装的方法,传入的参数的类型和具体包下的类。斜体样式