java获取 Response 中的 location属性-【抖音-douyin】
- 工作小总结
- 时间:2022-12-11 23:09
- 3890人已阅读
简介
需求:如图:得到页面上的location的值代码实现ps:参考:https://www.cnblogs.com/zhougaojun/p/4547160.htmlhttps://www.cnblogs.com/niss/p/3711901.htmlJsoup的实现public String json() throws IOException {&n
🔔🔔🔔好消息!好消息!🔔🔔🔔
有需要的朋友👉:联系凯哥
需求:

如图:得到 页面上的 location 的值
代码实现
插播一条
下面这个公众号是凯哥开发的,福利号:外卖、买菜、电商领Q的

怎么领券?

ps:参考: https://www.cnblogs.com/zhougaojun/p/4547160.html
https://www.cnblogs.com/niss/p/3711901.html
Jsoup 的实现
public String json() throws IOException {
Response execute = Jsoup.connect("https://www.freepik.com/download-file/1088379")
.followRedirects(false)
.method(Method.GET)
.execute();
return execute.headers("location").get(0);
}旧版httpclient
private String getMaxUrl(String img_downloard_url) {
String locale ="";
//创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpParams params = httpClient.getParams();
params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
//创建httpGet对象,设置url地址:
HttpGet httpGet = new HttpGet(img_downloard_url);
CloseableHttpResponse response= null;
try {
//使用httpClient发起请求 获取 response
response = httpClient.execute(httpGet);
//解析响应
if(response.getStatusLine().getStatusCode() == 302) {
org.apache.http.Header locationHeader = response.getFirstHeader("Location");
if(locationHeader!=null){
locale = locationHeader.getValue();
System.out.println(locale);
// LOG.info(MessageFormat.format("[{0}]|[成功{1}]|[url:{2}]|[status:{3}]|[{location:{4}}]",tag,responseCode,googleUrl,responseCode,location));
}
System.out.println(response.getAllHeaders());
locale = response.getFirstHeader("Location").getValue();
}
} catch (Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}finally {
try {
//关闭httpClient
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//关闭response
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return locale;
} 新版
private RequestConfig createConfig(int timeout, boolean redirectsEnabled)
{
retun RequestConfig.custom()
.setSocketTimeout(timeout)
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setRedirectsEnabled(redirectsEnabled)
.build();
}
public void test(String url)
{
CloseableHttpClient client = HttpClients.createDefault();
try
{
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(createConfig(5000, false));
CloseableHttpResponse response = client.execute(httpGet);
try
{
Header h = response.getFirstHeader("Location");
if(h!=null)
{
System.out.println("重定向地址:"+h.getValue());
}
}
finally
{
response.close();
}
}
finally
{
client.close();
}
}————————————————
版权声明:本文为CSDN博主「坐在西半球上」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:
https://blog.csdn.net/qq_42082278/article/details/105068527