android客户端HttpClient URL 被重定向的解决办法

  我们在开发时经常使用到网络请求,但是有时候会遇到服务端给的url不是最终的,我们用这个url在浏览器上链接下,会发现url改变了,这就是url不是最终的,而是被重定向后的链接地址。

  那我们如何解决这种问题呢,不多说,看代码:

public class HttpClientURLRedirectUtils {

/**
* Http URL重定向
*/
public static String redirect(String url) {
DefaultHttpClient httpclient = null;
try {
httpclient = new DefaultHttpClient();
httpclient.setRedirectHandler(new RedirectHandler() {

@Override
public boolean isRedirectRequested(HttpResponse response,
HttpContext context) {
return false;
}

@Override
public URI getLocationURI(HttpResponse response, HttpContext context)
throws org.apache.http.ProtocolException {
return null;
}
});

HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);

int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
// 打印响应内容长度
// System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
// System.out.println("Response content: " + EntityUtils.toString(entity));
}
} else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY
|| statusCode == HttpStatus.SC_MOVED_PERMANENTLY) {

// System.out.println("当前页面发生重定向了---");

org.apache.http.Header[] headers = response.getHeaders("Location");
if(headers!=null && headers.length>0){
String redirectUrl = headers[0].getValue();
// System.out.println("重定向的URL:"+redirectUrl);
redirectUrl = redirectUrl.replace(" ", "%20");
return redirectUrl;
}
}

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
httpclient.getConnectionManager().shutdown();
}
return url;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值