我正在尝试访问bgp 排名 url,但正在获取 html 页面作为输出,我想获取该hmtl 页面中的 json 数据。我们如何获取json 数据。
这是控制器,下面我给出了服务实现。任何机构都可以找出问题
这是 BGP 排名网址:https ://bgp.he.net
控制器
@RestController
@RequestMapping(value = "/api/bgp")
public class BGPController {
@Autowired
BGPService bgpService;
@RequestMapping(value = "/getInfoById/{query}", method = RequestMethod.POST)
protected @ResponseBody Map<String, Object> getAllJobs(@PathVariable(value = "query") String query) {
Map<String, Object> dataMap = new HashMap<String, Object>();
try {
dataMap.put("status", true);
dataMap.put("result", bgpService.getRanking(query));
} catch (Exception e) {
dataMap.put("status", false);
dataMap.put("reason", e.getMessage());
System.err.println("exception at bgp: ");
e.printStackTrace();
}
System.out.println("dataMap: " + dataMap.toString());
return dataMap;
}
}
服务实施
@Service
@Component
public class BGPServiceImpl implements BGPService {
static CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet getRequest = null;
CloseableHttpResponse response = null;
BufferedReader br = null;
String stringJson = null;
StringEntity stringEntity = null;
String output = null;
String URL = "https://bgp.he.net/";
@Override
public Map<String, Object> getRanking(String query) {
Map<String, Object> dataMap = new HashMap<>();
try {
getRequest = new HttpGet(URL + query);
response = httpClient.execute(getRequest);
br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String responseContent = "";
while ((output = br.readLine()) != null) {
responseContent += output;
}
if (response.getStatusLine().getStatusCode() == 200) {
dataMap.put("status", "success");
dataMap.put("rawData", responseContent);
} else {
dataMap.put("status", "failure");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("dataMap: " + dataMap);
return dataMap;
}
}