我有一个REST服务(Java 7),我通过REST客户端调用(Java 11)。
Maven依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
REST服务
@GET
@Path("trip/{tripId}")
@ApiOperation(value="Returns the details for a trip.")
@ApiResponses({
@ApiResponse(code=200, message="Success"),
@ApiResponse(code=404, message="Not Found")
})
@Produces({ MediaType.APPLICATION_JSON })
public Response getTripDetails(@HeaderParam("Authorization") String token, @Context HttpServletRequest request, @PathParam("tripId") final String tripId) {
super.init(jwtTokenUtil, memberService, travelAgencyFacade);
TripDetailsResponse tripDetailsResponse = new TripDetailsResponse();
try {
tripDetailsResponse.setTripId(tripId);
final Long tripIdL = Long.valueOf(tripId);
TripDTO tripDTO = trips.getTripDetails(tripIdL);
tripDetailsResponse.setTripDTO(null);
tripDetailsResponse.setStatus(ResourceConstants.SUCCESS_STATUS);
Response response = Response.ok().entity(tripDetailsResponse).build();
return response;
} catch (Exception e) {
return handleError(e, logger, tripDetailsResponse, true);
}
}
我在Postman中测试了REST服务,它返回了如下JSON:
{
"tripId": "1801855",
"tripDTO": null,
"messages": [],
"status": "success"
}
REST客户机
private Response callGETEndpoint(final String url) throws IOException, NoSuchAlgorithmException, KeyManagementException {
TrustManager[] trustAllCerts = getTrustManager();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.get()
.build();
okHttpClient.setSslSocketFactory(sc.getSocketFactory());
okHttpClient.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
logger.info(url);
try {
Response response = okHttpClient.newCall(request).execute();
return response;
} catch (SocketTimeoutException e) {
// try again
try {
Response response = okHttpClient.newCall(request).execute();
return response;
} catch (SocketTimeoutException ex) {
logger.error("Call to "+url+" timed out.", ex);
}
}
return null;
}
客户端调用
Response response = client.callGETEndpoint(url);
if (response != null && response.isSuccessful()) {
if (response.code() == 200) {
final ResponseBody responseBody = response.body();
final String responseString = responseBody.string();
响应的状态确实是200。但是,responseString
是空白的。我希望它包含在Postman响应中看到的数据。
我需要做什么才能从响应中获得正文?
您可以尝试解析
进口com.jayway.jsonpath.JsonPath;
…
ReadContext rContext = JsonPath.parse(response.body().string())