向服务器发送视频Url的请求时,经常会被重定向到另外一个界面,这个界面的地址URL可以在返回的Response的Location字段得到。
可以通过判断response的StatusCode来判断页面是否需要重定向,code为301(MOVED_PERMANENTLY)和302(MOVED_TEMPORARILY)时需要重定向。
注意:
mConnection.setInstanceFollowRedirects(false);
该句是获取重定向Response的关键,不做此设置,会直接获取被重定向之后的Response,这样就没有Location了。
private String getResponseLocation(String requestUrl) { String location = null; try { URL url = new URL(requestUrl); HttpURLConnection mConnection = (HttpURLConnection) url .openConnection(); mConnection.setInstanceFollowRedirects(false); mConnection.setRequestMethod("GET"); mConnection.setConnectTimeout(5 * 1000); mConnection.connect(); location = mConnection.getHeaderField("location"); } catch (MalformedURLException e) { // TODO Auto-generated catch block Log.d(TAG, "MalformedURLException"); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, "IOException"); e.printStackTrace(); } return location; }
也可以通过下面的方法打印出所有的ResponseHeader,但是没有找到获取重定向request的设置方法,所以下面的方法获取不到301和302的Response。
HttpGet httpGet = new HttpGet(targetWeb); RequestLine requestLine = httpGet.getRequestLine(); Log.d(TAG,"RequestLine:" + requestLine.toString()); HttpClient httpClient = new DefaultHttpClient();// 构造一个默认的HttpClient客户端对象 HttpResponse httpResponse = null; // 定义一个HttpResponse响应对象 HttpEntity httpEntity = null; // 定义一个 HttpEntity响应内容实体 InputStream is = null; try { httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { printResponse_AllHeader(httpResponse); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); is = null; } catch (IOException e) { e.printStackTrace(); } } } private void printResponse_AllHeader(HttpResponse httpResponse) { // 获取响应中所有的 Header Header[] arrHeader = httpResponse.getAllHeaders(); Log.d(TAG,"=====所有的 Header begin====="); for (int i = 0; i < arrHeader.length; i++) { Header hearder = arrHeader[i]; Log.d(TAG,"hearder.getName() = " + hearder.getName() + " hearder.getValue() = " + hearder.getValue()); } Log.d(TAG,"=====所有的 Header end====="); }