java.net.HttpURLConnection#HTTP_MOVED_TEMP源码实例Demo

下面列出了java.net.HttpURLConnection#HTTP_MOVED_TEMP 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: MediaSDK   文件: HttpUtils.java
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);
}
 
源代码2 项目: arthas   文件: DownloadUtils.java
/**
 * 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;
}
 
源代码3 项目: visualvm   文件: NetworkOptionsModel.java
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;
}
 
源代码4 项目: zxingfragmentlib   文件: HttpHelper.java
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();
  }
}
 
源代码5 项目: rapidminer-studio   文件: UrlFollower.java
/**
 * 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;
	}
}
 
源代码6 项目: fresco   文件: HttpUrlConnectionNetworkFetcher.java
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;
  }
}
 
源代码7 项目: jus   文件: RedirectPolicy.java
@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;
}
 
源代码8 项目: morpheus-core   文件: HttpClient.java
/**
 * 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;
    }
}
 
源代码9 项目: PRDownloader   文件: Utils.java
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;
}
 
源代码10 项目: lams   文件: WebWindow.java
/**
 * 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;
}
 
源代码11 项目: ZXing-Standalone-library   文件: HttpHelper.java
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");
}
 
源代码12 项目: Study_Android_Demo   文件: HttpHelper.java
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();
  }
}
 
源代码13 项目: Aria   文件: M3U8ThreadTaskAdapter.java
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();
}
 
源代码14 项目: weex   文件: HttpHelper.java
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");
}
 
源代码15 项目: cloudflare-scrape-Android   文件: Cloudflare.java
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;
}
 
源代码17 项目: Telegram-FOSS   文件: DefaultHttpDataSource.java
/**
 * 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);
}
 
源代码18 项目: TelePlus-Android   文件: DefaultHttpDataSource.java
/**
 * 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);
}
 
源代码19 项目: cxf   文件: URIResolver.java
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"));
}
 
源代码20 项目: cloudflare-scrape-Android   文件: Cloudflare.java
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;
    }
}