我们在开发时经常使用到网络请求,但是有时候会遇到服务端给的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;
}
}