1、在浏览器上打开A网页,正常
2、用postman访问A网页,也正常
3、用httpclient访问A网页,却显示404
报错如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /xxx/yyy/zzz</pre>
</body>
</html>
已知A网页是用vue写的
后来加多请求头就解决了
private String get(String url){
String content = "";
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Get请求
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("accept", "*/*");
httpGet.addHeader("connection", "Keep-Alive");
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
content = EntityUtils.toString(responseEntity);
System.out.println("响应内容为:" + content);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
关键点:
httpGet.addHeader("accept", "*/*");
httpGet.addHeader("connection", "Keep-Alive");