用Head方法获得百度搜索结果的真实地址

在百度中搜索“Java”,第一条结果的链接为:

https://www.baidu.com/link?url=HBOOMbhPKH4SfI0vCLVSSJ3W1eNGX1wjwg6q4hna6L3&wd=&eqid=f7bdf9e40005b5820000000357e76187

因此需要设法将其转换为真实的网站链接:http://www.java.com/

用Head方法获得百度搜索结果的真实地址-LMLPHP

思路很简单:

  1. 使用 HTTP HEAD方法 ,会返回302 Move Permanently
  2. 在Respons Headers中查看Location中的内容,即为要跳转到的真实地址。

使用命令行工具HttpIE试验如下:

E:\>http head https://www.baidu.com/link?url=HBOOMbhPKH4SfI0vCLVSSJ3W1eNGX1wjwg6q4hna6L3&wd=&eqid=f7bdf9e40005b5820000000357e76187
HTTP/1.1 302 Moved Temporarily
BDPAGETYPE: 3
Cache-Control: no-cache, must-revalidate
Connection: keep-alive
Content-Length: 215
Content-Type: text/html;charset=utf8
Date: Sun, 25 Sep 2016 05:40:07 GMT
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Location: http://www.java.com/
Pragma: no-cache
Server: bfe/1.0.8.18
Set-Cookie: BDSVRTM=0; path=/
X-UA-Compatible: IE=Edge,chrome=1
X-XSS-Protection: 1;mode=block

最后编写Java代码如下:

public static String getRealLinkFromBaiduLink(String link){
// 需要注意的是,这里必须 disableRedirectHandling,否则会自动进行地址的跳转
CloseableHttpClient httpClient = HttpClients.custom().disableRedirectHandling().build();
// 这里可以使用Http Head 方法
HttpHead httpHead = new HttpHead(link);
try (CloseableHttpResponse response = httpClient.execute(httpHead)) {
int status = response.getStatusLine().getStatusCode();
if (status == 302) {
return response.getFirstHeader("Location").getValue();
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
05-04 05:17