目标实现描述:用户发送HTTP请求后,后台Controller层接收请求后获取对应的参数,将参数拼接到对应的第三方接口中,然后建立连接,向第三方库发送请求,获取对应的数据,然后对数据进行相应的处理!
直接上代码,详情看注释!
@Controller
public class TransportController implements WebMvcConfigurer {
private static String key = "对自己第三方开发者账号的KEY";
private static Logger logger = LoggerFactory.getLogger(TransportController.class);
@Autowired
UrlService urlService;
/**
* 表单验证中,用于页面重定向,需要注册将要重定向到的视图
*
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/transportCondition").setViewName("transportCondition");
}
@GetMapping("/index")
public String start(){
return "index";
}
@PostMapping("/cond")
public ModelAndView condition(@RequestParam(name = "longitude",defaultValue = "114.1358180155")String longitude,
@RequestParam(name = "latitude",defaultValue = "22.5544420000")String latitude,
@RequestParam(name = "radius",defaultValue = "500")String radius,
Model model){
String url = " https://restapi.amap.com/v3/traffic/status/circle?location="+longitude+","+latitude+"&radius="+radius+"&key="+key;
JSONObject jsonObject = urlService.sendUrlRequest(url);
String description = jsonObject.get("trafficinfo").toString();
logger.info(description);
/**
* 设置一个JSONArray数组,添加时间、道路、水深和路况的信息
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, TimeUtil.timeStamp2Sdf());
jsonArray.add(1,"XXXXX道路");
jsonArray.add(2,description);*/
//将数据添加到Model中,传输到前台
model.addAttribute("desc",description);
// model.addAttribute("jsonArray",jsonArray);
// return description;
// return "redirect:/transportCondition"; //此方法获取的数据为空 ??
return new ModelAndView("transportCondition");
}
}
Service层的业务逻辑处理
package com.dzg.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
@Service(value = "urlService")
public class UrlService {
public JSONObject sendUrlRequest(String requestUrl){
JSONObject jsonObject = null;
try {
URL url = new URL(requestUrl);
//得到connection连接对象
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//设置请求的方式
urlConnection.setRequestMethod("GET");
//连接
urlConnection.connect();
//得到响应码
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
//得到响应流
InputStream inputStream = urlConnection.getInputStream();
//获取响应的数据
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder content = new StringBuilder();
String line;
while((line = bufferedReader.readLine()) != null){
content.append(line);
}
jsonObject = (JSONObject) JSON.parse(content.toString());
bufferedReader.close();
//断开连接
urlConnection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
}
参考链接:
https://blog.csdn.net/neymar_jr/article/details/79192812