我正在尝试使用Google距离矩阵API创建一个显示2点之间距离的代码。但是,当我尝试通过Postman运行它时,出现错误:Unexpected '<'
。我不知道如何显示如下响应:
{
"destination_addresses" : [ "San Francisco, Californie, États-Unis" ],
"origin_addresses" : [ "Seattle, Washington, États-Unis" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1 300 km",
"value" : 1299878
},
"duration" : {
"text" : "12 heures 32 minutes",
"value" : 45146
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
提供了DistanceController
:
@RestController
@CrossOrigin(value = "*")
@RequestMapping(value = "/distance")
public class DistanceController {
private final DistanceService distanceService;
@Autowired
public DistanceController(DistanceService distanceService) {
this.distanceService = distanceService;
}
@RequestMapping(value = "/distance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> calculate(
@RequestBody DistanceCalculationDTO request) throws IOException {
String response = distanceService.distanceCalculation(request);
try{
return new ResponseEntity<>(response, HttpStatus.OK);
} catch (Exception e){
return new ResponseEntity<>(response, HttpStatus.OK);
}
}
}
提供了DistanceServiceImpl
:
@Service
public class DistanceServiceImpl implements DistanceService {
@Autowired
DistanceService distanceService;
private static final String API_KEY = "";
OkHttpClient client = new OkHttpClient();
@Override
public String distanceCalculation(Distance request)
throws IOException {
String url = "https://maps.googleapis.com/map/api/distancematrix/json?origins=" +
request.getOrigin() + "&destination" + request.getDestination() + API_KEY;
Request request2 = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request2).execute();
return response.body().string();
}
}
您能否至少分享一个有关如何实现我期望的JSON响应的示例?