您可以在 url 中使用 'r=' 查询参数来获取重定向所指向的确切 url。一个示例 bing url 看起来像这样
"url": "http://www.bing.com/cr?IG=584DA9A5C8B245DDA12848B177BAF817&CID=138CDEBD227860443797D43D239D616C&rd=1&h=0UIFjW9hoNBrd0LFRhopxM1IDwbKCHvSc-z-FdLfyMQ&v=1&r=http%3a%2f%2fallrecipes.com%2frecipes%2f1216%2fworld-cuisine%2flatin-american%2fmexican%2fmain-dishes%2fburritos%2f&p=DevEx,5066.1"
这里,
r=http%3a%2f%2fallrecipes.com%2frecipes%2f1216%2fworld-cuisine%2flatin-american%2fmexican%2fmain-dishes%2fburritos%2f
请注意,url 是编码的。如果需要,执行 url 解码。所有这些都可以使用以下 Java 代码来完成。
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.log4j.Logger;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public static String getExactUrl(String url) {
Map<String, String> queryParams = getQueryParamsMap(url);
return queryParams.getOrDefault("r", url);
}
public static Map<String, String> getQueryParamsMap(String url) {
Map<String, String> queryParamsMap = new HashMap<>();
try {
URIBuilder uriBuilder = new URIBuilder(url);
List<NameValuePair> queryParams = uriBuilder.getQueryParams();
queryParamsMap = queryParams.stream().collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));
} catch (URISyntaxException e) {
e.printStackTrace();
}
return queryParamsMap;
}