HttpUrlConnection访问重定向接口

在Java爬虫项目中,面对重定向的图片链接,需要直接获取重定向后的URL。通过Chrome开发者工具查看,重定向地址位于Response Headers的Location字段。HttpURLConnection提供了setInstanceFollowRedirects方法关闭自动重定向,再使用getHeaderField('Location')获取重定向链接。
摘要由CSDN通过智能技术生成

最近在做一个爬虫项目,需要抓取一些网站的资讯和其中的图片,抓取过程中发现有一些图片链接会重定向,而服务器存储时不支持重定向,于是想尝试直接拿到重定向的链接。
借助Chrome浏览器的开发者工具(快捷键F12),选择Network -> Headers,可以看到其重定向后的地址在Response Headers中的Location属性中。

查阅资料文档可知,
1.类HttpURLConnection提供了如下方法:

public void setInstanceFollowRedirects(boolean followRedirects)

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.
The default value comes from followRedirects, which defaults to true.
Parameters:
followRedirects a boolean indicating whether or not to follow HTTP redirects.

2.其父类URLConnection有如下方法:

public String getHeaderField(String name)

Returns the value of the named header field.
If called on a connection that sets the same header multiple times with possibly different values, only the last value is returned.
Parameters:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值