下面列出了java.net.HttpURLConnection#HTTP_MOVED_TEMP 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static URL handleRedirectRequest(LocalProxyConfig config, URL url, HashMap<String, String> headers) throws IOException {
int redirectCount = 0;
while (redirectCount++ < MAX_REDIRECT) {
HttpURLConnection connection = makeConnection(config, url, headers);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MULT_CHOICE
|| responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER
&& (responseCode == 307 /* HTTP_TEMP_REDIRECT */
|| responseCode == 308 /* HTTP_PERM_REDIRECT */)) {
String location = connection.getHeaderField("Location");
connection.disconnect();
url = handleRedirect(url, location);
return handleRedirectRequest(config, url, headers);
} else {
return url;
}
}
throw new NoRouteToHostException("Too many redirects: " + redirectCount);
}
/**
* support redirect
*
* @param url
* @return
* @throws MalformedURLException
* @throws IOException
*/
private static URLConnection openURLConnection(String url) throws MalformedURLException, IOException {
URLConnection connection = new URL(url).openConnection();
if (connection instanceof HttpURLConnection) {
connection.setConnectTimeout(CONNECTION_TIMEOUT);
// normally, 3xx is redirect
int status = ((HttpURLConnection) connection).getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER) {
String newUrl = connection.getHeaderField("Location");
AnsiLog.debug("Try to open url: {}, redirect to: {}", url, newUrl);
return openURLConnection(newUrl);
}
}
}
return connection;
}
private static boolean testHttpConnection(URL url, Proxy proxy) throws IOException {
boolean result = false;
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(proxy);
// Timeout shorten to 5s
httpConnection.setConnectTimeout(5000);
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK
|| httpConnection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
result = true;
}
httpConnection.disconnect();
return result;
}
public static URI unredirect(URI uri) throws IOException {
if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) {
return uri;
}
URL url = uri.toURL();
HttpURLConnection connection = safelyOpenConnection(url);
connection.setInstanceFollowRedirects(false);
connection.setDoInput(false);
connection.setRequestMethod("HEAD");
connection.setRequestProperty("User-Agent", "ZXing (Android)");
try {
int responseCode = safelyConnect(connection);
switch (responseCode) {
case HttpURLConnection.HTTP_MULT_CHOICE:
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
case HttpURLConnection.HTTP_SEE_OTHER:
case 307: // No constant for 307 Temporary Redirect ?
String location = connection.getHeaderField("Location");
if (location != null) {
try {
return new URI(location);
} catch (URISyntaxException e) {
// nevermind
}
}
}
return uri;
} finally {
connection.disconnect();
}
}
/**
* Checks if the connection is redirecting
*
* @param connection the connection to check
* @return true if the response code is a redirect code
*
* @throws IOException if an error occurred connecting to the server.
*/
private static boolean isRedirecting(HttpURLConnection connection) throws IOException {
switch (connection.getResponseCode()) {
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
case HttpURLConnection.HTTP_SEE_OTHER:
case TEMPORARY_REDIRECT:
case PERMANENT_REDIRECT:
return true;
default:
return false;
}
}
private static boolean isHttpRedirect(int responseCode) {
switch (responseCode) {
case HttpURLConnection.HTTP_MULT_CHOICE:
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
case HttpURLConnection.HTTP_SEE_OTHER:
case HTTP_TEMPORARY_REDIRECT:
case HTTP_PERMANENT_REDIRECT:
return true;
default:
return false;
}
}
@Override
public Request verifyRedirect(final Request request, NetworkResponse networkResponse) {
Request res = null;
if (networkResponse != null && networkResponse.headers != null
&& networkResponse.headers.get("location") != null && (
networkResponse.statusCode == HttpURLConnection.HTTP_MULT_CHOICE
|| networkResponse.statusCode == HttpURLConnection.HTTP_MOVED_PERM
|| networkResponse.statusCode == HttpURLConnection.HTTP_MOVED_TEMP
|| networkResponse.statusCode == HttpURLConnection.HTTP_SEE_OTHER
|| networkResponse.statusCode == 307
|| networkResponse.statusCode == 308
)) {
HttpUrl url = request.getUrl().resolve(networkResponse.headers.get("location"));
if (networkResponse.statusCode == HttpURLConnection.HTTP_SEE_OTHER) {
res = new Request(Request.Method.GET, url)
.setNetworkRequest(new NetworkRequest.Builder()
.addHeaders(request.getNetworkRequest().headers).build());
} else {
res = new Request(request.getMethod(), url)
.setNetworkRequest(request.getNetworkRequest());
}
res.setRetryPolicy(request.getRetryPolicy())
.setRedirectPolicy(request.getRedirectPolicy())
.addMarkerListener(new RequestListener.MarkerListener() {
@Override
public void onMarker(Marker marker, Object... args) {
request.addMarker(marker.name, args);
}
});
}
return res;
}
/**
* Returns true if the status code implies the resource has moved
* @param statusCode the HTTP status code
* @return true if resource has moved
*/
private boolean hasMoved(int statusCode) {
switch (statusCode) {
case HttpURLConnection.HTTP_MOVED_TEMP: return true;
case HttpURLConnection.HTTP_MOVED_PERM: return true;
case HttpURLConnection.HTTP_SEE_OTHER: return true;
default: return false;
}
}
private static boolean isRedirection(int code) {
return code == HttpURLConnection.HTTP_MOVED_PERM
|| code == HttpURLConnection.HTTP_MOVED_TEMP
|| code == HttpURLConnection.HTTP_SEE_OTHER
|| code == HttpURLConnection.HTTP_MULT_CHOICE
|| code == Constants.HTTP_TEMPORARY_REDIRECT
|| code == Constants.HTTP_PERMANENT_REDIRECT;
}
/**
* check whether redirect is configured
* @param response
* @return
*/
private boolean redirectConfigured( WebResponse response ) {
boolean isAutoredirect=getClient().getClientProperties().isAutoRedirect();
boolean hasLocation=response.getHeaderField( "Location" ) != null;
int responseCode=response.getResponseCode();
boolean result=isAutoredirect
&& responseCode >= HttpURLConnection.HTTP_MOVED_PERM
&& responseCode <= HttpURLConnection.HTTP_MOVED_TEMP
&& hasLocation;
return result;
}
private static CharSequence downloadViaHttp(String uri, String contentTypes, int maxChars) throws IOException {
int redirects = 0;
while (redirects < 5) {
URL url = new URL(uri);
HttpURLConnection connection = safelyOpenConnection(url);
connection.setInstanceFollowRedirects(true); // Won't work HTTP -> HTTPS or vice versa
connection.setRequestProperty("Accept", contentTypes);
connection.setRequestProperty("Accept-Charset", "utf-8,*");
connection.setRequestProperty("User-Agent", "ZXing (Android)");
try {
int responseCode = safelyConnect(connection);
switch (responseCode) {
case HttpURLConnection.HTTP_OK:
return consume(connection, maxChars);
case HttpURLConnection.HTTP_MOVED_TEMP:
String location = connection.getHeaderField("Location");
if (location != null) {
uri = location;
redirects++;
continue;
}
throw new IOException("No Location");
default:
throw new IOException("Bad HTTP response: " + responseCode);
}
} finally {
connection.disconnect();
}
}
throw new IOException("Too many redirects");
}
public static URI unredirect(URI uri) throws IOException {
if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) {
return uri;
}
URL url = uri.toURL();
HttpURLConnection connection = safelyOpenConnection(url);
connection.setInstanceFollowRedirects(false);
connection.setDoInput(false);
connection.setRequestMethod("HEAD");
connection.setRequestProperty("User-Agent", "ZXing (Android)");
try {
int responseCode = safelyConnect(connection);
switch (responseCode) {
case HttpURLConnection.HTTP_MULT_CHOICE:
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
case HttpURLConnection.HTTP_SEE_OTHER:
case 307: // No constant for 307 Temporary Redirect ?
String location = connection.getHeaderField("Location");
if (location != null) {
try {
return new URI(location);
} catch (URISyntaxException e) {
// nevermind
}
}
}
return uri;
} finally {
connection.disconnect();
}
}
private void handleConn(HttpURLConnection conn) throws IOException {
ConnectionHelp.setConnectParam(mHttpTaskOption, conn);
conn.setConnectTimeout(getTaskConfig().getConnectTimeOut());
conn.setReadTimeout(getTaskConfig().getIOTimeOut()); //设置读取流的等待时间,必须设置该参数
conn.connect();
int code = conn.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
is = new BufferedInputStream(ConnectionHelp.convertInputStream(conn));
if (mHttpTaskOption.isChunked()) {
readChunked(is);
} else if (getThreadConfig().isBlock) {
readDynamicFile(is);
}
} else if (code == HttpURLConnection.HTTP_MOVED_TEMP
|| code == HttpURLConnection.HTTP_MOVED_PERM
|| code == HttpURLConnection.HTTP_SEE_OTHER
|| code == HttpURLConnection.HTTP_CREATED // 201 跳转
|| code == 307) {
handleUrlReTurn(conn, conn.getHeaderField("Location"));
} else {
fail(new AriaM3U8Exception(
String.format("连接错误,http错误码:%s,url:%s", code, getThreadConfig().url)),
false);
}
conn.disconnect();
}
private static CharSequence downloadViaHttp(String uri, String contentTypes, int maxChars) throws IOException {
int redirects = 0;
while (redirects < 5) {
URL url = new URL(uri);
HttpURLConnection connection = safelyOpenConnection(url);
connection.setInstanceFollowRedirects(true); // Won't work HTTP -> HTTPS or vice versa
connection.setRequestProperty("Accept", contentTypes);
connection.setRequestProperty("Accept-Charset", "utf-8,*");
connection.setRequestProperty("User-Agent", "ZXing (Android)");
try {
int responseCode = safelyConnect(connection);
switch (responseCode) {
case HttpURLConnection.HTTP_OK:
return consume(connection, maxChars);
case HttpURLConnection.HTTP_MOVED_TEMP:
String location = connection.getHeaderField("Location");
if (location != null) {
uri = location;
redirects++;
continue;
}
throw new IOException("No Location");
default:
throw new IOException("Bad HTTP response: " + responseCode);
}
} finally {
connection.disconnect();
}
}
throw new IOException("Too many redirects");
}
private void getRedirectResponse(AnswerBean answerBean) throws IOException {
HttpURLConnection.setFollowRedirects(false);
mGetRedirectionConn = (HttpURLConnection) new URL(answerBean.getHost()).openConnection();
mGetRedirectionConn.setRequestMethod(answerBean.getMethod() == AnswerBean.GET ? "GET" : "POST");
mGetRedirectionConn.setConnectTimeout(CONN_TIMEOUT);
mGetRedirectionConn.setReadTimeout(CONN_TIMEOUT);
mGetRedirectionConn.setDoInput(true);
mGetRedirectionConn.setDoOutput(true);
mGetRedirectionConn.setUseCaches(false);
if (!TextUtils.isEmpty(mUser_agent)){
mGetRedirectionConn.setRequestProperty("user-agent",mUser_agent);
}
mGetRedirectionConn.setRequestProperty("accept",ACCEPT);
mGetRedirectionConn.setRequestProperty("referer", mUrl);
if (mCookieList!=null&&mCookieList.size()>0){
mGetRedirectionConn.setRequestProperty("cookie",listToString(mCookieList));
}
mGetRedirectionConn.setUseCaches(false);
if (answerBean.getMethod() == AnswerBean.POST){
mGetRedirectionConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
mGetRedirectionConn.connect();
if (answerBean.getMethod() == AnswerBean.POST){
StringBuilder stringBuilder = new StringBuilder();
for(Map.Entry<String, String> entry :answerBean.getFromData().entrySet()){
stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
stringBuilder.deleteCharAt(stringBuilder.length()-1);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mGetRedirectionConn.getOutputStream(), "UTF-8"));
writer.write(stringBuilder.toString());
writer.close();
}
switch (mGetRedirectionConn.getResponseCode()){
case HttpURLConnection.HTTP_OK:
mCookieList = mCookieManager.getCookieStore().getCookies();
break;
case HttpURLConnection.HTTP_MOVED_TEMP:
mCookieList = mCookieManager.getCookieStore().getCookies();
checkCookie(mCookieList);
break;
default:throw new IOException("getOtherResponse Code: "+
mGetRedirectionConn.getResponseCode());
}
}
static boolean needRedirects(int responseCode) {
return responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HTTP_307;
}
/**
* Establishes a connection, following redirects to do so where permitted.
*/
private HttpURLConnection makeConnection(DataSpec dataSpec) throws IOException {
URL url = new URL(dataSpec.uri.toString());
@HttpMethod int httpMethod = dataSpec.httpMethod;
byte[] httpBody = dataSpec.httpBody;
long position = dataSpec.position;
long length = dataSpec.length;
boolean allowGzip = dataSpec.isFlagSet(DataSpec.FLAG_ALLOW_GZIP);
boolean allowIcyMetadata = dataSpec.isFlagSet(DataSpec.FLAG_ALLOW_ICY_METADATA);
if (!allowCrossProtocolRedirects) {
// HttpURLConnection disallows cross-protocol redirects, but otherwise performs redirection
// automatically. This is the behavior we want, so use it.
return makeConnection(
url,
httpMethod,
httpBody,
position,
length,
allowGzip,
allowIcyMetadata,
/* followRedirects= */ true);
}
// We need to handle redirects ourselves to allow cross-protocol redirects.
int redirectCount = 0;
while (redirectCount++ <= MAX_REDIRECTS) {
HttpURLConnection connection =
makeConnection(
url,
httpMethod,
httpBody,
position,
length,
allowGzip,
allowIcyMetadata,
/* followRedirects= */ false);
int responseCode = connection.getResponseCode();
String location = connection.getHeaderField("Location");
if ((httpMethod == DataSpec.HTTP_METHOD_GET || httpMethod == DataSpec.HTTP_METHOD_HEAD)
&& (responseCode == HttpURLConnection.HTTP_MULT_CHOICE
|| responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER
|| responseCode == HTTP_STATUS_TEMPORARY_REDIRECT
|| responseCode == HTTP_STATUS_PERMANENT_REDIRECT)) {
connection.disconnect();
url = handleRedirect(url, location);
} else if (httpMethod == DataSpec.HTTP_METHOD_POST
&& (responseCode == HttpURLConnection.HTTP_MULT_CHOICE
|| responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER)) {
// POST request follows the redirect and is transformed into a GET request.
connection.disconnect();
httpMethod = DataSpec.HTTP_METHOD_GET;
httpBody = null;
url = handleRedirect(url, location);
} else {
return connection;
}
}
// If we get here we've been redirected more times than are permitted.
throw new NoRouteToHostException("Too many redirects: " + redirectCount);
}
/**
* Establishes a connection, following redirects to do so where permitted.
*/
private HttpURLConnection makeConnection(DataSpec dataSpec) throws IOException {
URL url = new URL(dataSpec.uri.toString());
byte[] postBody = dataSpec.postBody;
long position = dataSpec.position;
long length = dataSpec.length;
boolean allowGzip = dataSpec.isFlagSet(DataSpec.FLAG_ALLOW_GZIP);
if (!allowCrossProtocolRedirects) {
// HttpURLConnection disallows cross-protocol redirects, but otherwise performs redirection
// automatically. This is the behavior we want, so use it.
return makeConnection(url, postBody, position, length, allowGzip, true /* followRedirects */);
}
// We need to handle redirects ourselves to allow cross-protocol redirects.
int redirectCount = 0;
while (redirectCount++ <= MAX_REDIRECTS) {
HttpURLConnection connection = makeConnection(
url, postBody, position, length, allowGzip, false /* followRedirects */);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MULT_CHOICE
|| responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER
|| (postBody == null
&& (responseCode == 307 /* HTTP_TEMP_REDIRECT */
|| responseCode == 308 /* HTTP_PERM_REDIRECT */))) {
// For 300, 301, 302, and 303 POST requests follow the redirect and are transformed into
// GET requests. For 307 and 308 POST requests are not redirected.
postBody = null;
String location = connection.getHeaderField("Location");
connection.disconnect();
url = handleRedirect(url, location);
} else {
return connection;
}
}
// If we get here we've been redirected more times than are permitted.
throw new NoRouteToHostException("Too many redirects: " + redirectCount);
}
private static boolean followRedirect(int status) {
return (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
&& Boolean.parseBoolean(SystemPropertyAction.getPropertyOrNull("http.autoredirect"));
}
private void getVisitCookie() throws IOException, InterruptedException {
ConnUrl = new URL(mUrl);
mGetMainConn = (HttpURLConnection) ConnUrl.openConnection();
mGetMainConn.setRequestMethod("GET");
mGetMainConn.setConnectTimeout(CONN_TIMEOUT);
mGetMainConn.setReadTimeout(CONN_TIMEOUT);
if (!TextUtils.isEmpty(mUser_agent)){
mGetMainConn.setRequestProperty("user-agent",mUser_agent);
}
mGetMainConn.setRequestProperty("accept",ACCEPT);
mGetMainConn.setRequestProperty("referer", mUrl);
if (mCookieList!=null&&mCookieList.size()>0){
mGetMainConn.setRequestProperty("cookie",listToString(mCookieList));
}
mGetMainConn.setUseCaches(false);
mGetMainConn.connect();
switch (mGetMainConn.getResponseCode()){
case HttpURLConnection.HTTP_OK:
e("MainUrl","visit website success");
mCookieList = mCookieManager.getCookieStore().getCookies();
checkCookie(mCookieList);
return;
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
hasNewUrl = true;
mUrl = mGetMainConn.getHeaderField("Location");
mCookieList = mCookieManager.getCookieStore().getCookies();
checkCookie(mCookieList);
e("MainUrl","HTTP 301 :"+mUrl);
return;
case HttpURLConnection.HTTP_FORBIDDEN:
e("MainUrl","IP block or cookie err");
return;
case HttpURLConnection.HTTP_UNAVAILABLE:
InputStream mInputStream = mCheckConn.getErrorStream();
BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream));
StringBuilder sb = new StringBuilder();
String str;
while ((str = mBufferedReader.readLine()) != null){
sb.append(str);
}
mInputStream.close();
mBufferedReader.close();
mCookieList = mCookieManager.getCookieStore().getCookies();
str = sb.toString();
getCheckAnswer(str);
break;
default:
e("MainUrl","UnCatch Http code: "+mGetMainConn.getHeaderField("Location"));
break;
}
}