HTTP_SEE_OTHER源码实例Demo

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

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

源代码1 项目: takes   文件: RsWithStatusTest.java
/**
 * RsWithStatus can add status multiple times.
 */
@SuppressWarnings(
    {
        "PMD.JUnitTestContainsTooManyAsserts",
        "PMD.ProhibitPlainJunitAssertionsRule"
    }
)
@Test
public void addsStatusMultipleTimes() {
    final Response response = new RsWithStatus(
        new RsWithStatus(
            new RsEmpty(),
            HttpURLConnection.HTTP_NOT_FOUND
        ),
        HttpURLConnection.HTTP_SEE_OTHER
    );
    final Assertion<Scalar<Iterable<?>>> assertion = new Assertion<>(
        "Head with one line",
        response::head,
        new ScalarHasValue<>(new HasSize(1))
    );
    assertion.affirm();
    assertion.affirm();
}
 
源代码2 项目: jrpip   文件: Libboot.java
private static URLConnection handleRedirect(URLConnection urlConnection, int retriesLeft) throws IOException
{
    if (retriesLeft == 0)
    {
        throw new IOException("too many redirects connecting to "+urlConnection.getURL().toString());
    }
    if (urlConnection instanceof HttpURLConnection)
    {
        HttpURLConnection conn = (HttpURLConnection) urlConnection;

        int status = conn.getResponseCode();
        if (status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_SEE_OTHER)
        {
            String newUrl = conn.getHeaderField("Location");
            return handleRedirect(new URL(newUrl).openConnection(), retriesLeft - 1);
        }
    }
    return urlConnection;
}
 
源代码3 项目: reladomo   文件: Libboot.java
private static URLConnection handleRedirect(URLConnection urlConnection, int retriesLeft) throws IOException
{
    if (retriesLeft == 0)
    {
        throw new IOException("too many redirects connecting to "+urlConnection.getURL().toString());
    }
    if (urlConnection instanceof HttpURLConnection)
    {
        HttpURLConnection conn = (HttpURLConnection) urlConnection;

        int status = conn.getResponseCode();
        if (status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_SEE_OTHER)
        {
            String newUrl = conn.getHeaderField("Location");
            return handleRedirect(new URL(newUrl).openConnection(), retriesLeft - 1);
        }
    }
    return urlConnection;
}
 
源代码4 项目: tools   文件: ListedLicenses.java
public static String getNestedURL(String stringUrl) throws MalformedURLException {
	URL url = new URL(stringUrl);
	try {
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setInstanceFollowRedirects(false);
		con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
		con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
		con.addRequestProperty("Referer", "https://www.google.com/");
		con.connect();
		int resultCode = con.getResponseCode();
		if (resultCode == HttpURLConnection.HTTP_SEE_OTHER
				|| resultCode == HttpURLConnection.HTTP_MOVED_PERM
				|| resultCode == HttpURLConnection.HTTP_MOVED_TEMP) {
			String Location = con.getHeaderField("Location");
			if (Location.startsWith("/")) {
				Location = url.getProtocol() + "://" + url.getHost() + Location;
			}
			return getNestedURL(Location);
		}
	} catch (Exception e) {
		System.out.println(e.getMessage());
	}
	return url.toString();
}
 
源代码5 项目: windup   文件: EnhancedEntityResolver2.java
private boolean isRedirect(int status)
{
    return (status != HttpURLConnection.HTTP_OK) &&
            (status == HttpURLConnection.HTTP_MOVED_TEMP
                    || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER);
}
 
源代码6 项目: 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;
}
 
源代码7 项目: BarcodeEye   文件: 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(uri.toString(), 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();
  }
}
 
源代码8 项目: 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;
}
 
源代码9 项目: FileDownloader   文件: RedirectHandler.java
private static boolean isRedirect(int code) {
    return code == HttpURLConnection.HTTP_MOVED_PERM
            || code == HttpURLConnection.HTTP_MOVED_TEMP
            || code == HttpURLConnection.HTTP_SEE_OTHER
            || code == HttpURLConnection.HTTP_MULT_CHOICE
            || code == HTTP_TEMPORARY_REDIRECT
            || code == HTTP_PERMANENT_REDIRECT;
}
 
源代码10 项目: Dashchan   文件: HttpClient.java
void checkResponseCode(HttpHolder holder) throws HttpException {
	int responseCode = holder.getResponseCode();
	boolean success = responseCode >= HttpURLConnection.HTTP_OK && responseCode <= HttpURLConnection.HTTP_SEE_OTHER
			|| responseCode == HTTP_TEMPORARY_REDIRECT;
	if (!success) {
		String originalMessage = holder.getResponseMessage();
		String message = SHORT_RESPONSE_MESSAGES.get(originalMessage);
		if (message == null) {
			message = originalMessage;
		}
		holder.disconnectAndClear();
		throw new HttpException(responseCode, message);
	}
}
 
源代码11 项目: weex   文件: 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();
  }
}
 
源代码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 项目: Sentry-Android   文件: Sentry.java
/**
 * Map from HTTP status code to reason description.
 * Sentry HTTP breadcrumbs expect a text description of the HTTP status-code.
 * This function implements a look-up table with a default value for unknown status-codes.
 * @param statusCode an integer HTTP status code, expected to be in the range [200,505].
 * @return a non-empty string in all cases.
 */
private static String httpReason(int statusCode) {
    switch (statusCode) {
        // 2xx
        case HttpURLConnection.HTTP_OK: return "OK";
        case HttpURLConnection.HTTP_CREATED: return "Created";
        case HttpURLConnection.HTTP_ACCEPTED: return "Accepted";
        case HttpURLConnection.HTTP_NOT_AUTHORITATIVE: return "Non-Authoritative Information";
        case HttpURLConnection.HTTP_NO_CONTENT: return "No Content";
        case HttpURLConnection.HTTP_RESET: return "Reset Content";
        case HttpURLConnection.HTTP_PARTIAL: return "Partial Content";

        // 3xx
        case HttpURLConnection.HTTP_MULT_CHOICE: return "Multiple Choices";
        case HttpURLConnection.HTTP_MOVED_PERM: return "Moved Permanently";
        case HttpURLConnection.HTTP_MOVED_TEMP: return "Temporary Redirect";
        case HttpURLConnection.HTTP_SEE_OTHER: return "See Other";
        case HttpURLConnection.HTTP_NOT_MODIFIED: return "Not Modified";
        case HttpURLConnection.HTTP_USE_PROXY: return "Use Proxy";

        // 4xx
        case HttpURLConnection.HTTP_BAD_REQUEST: return "Bad Request";
        case HttpURLConnection.HTTP_UNAUTHORIZED: return "Unauthorized";
        case HttpURLConnection.HTTP_PAYMENT_REQUIRED: return "Payment Required";
        case HttpURLConnection.HTTP_FORBIDDEN: return "Forbidden";
        case HttpURLConnection.HTTP_NOT_FOUND: return "Not Found";
        case HttpURLConnection.HTTP_BAD_METHOD: return "Method Not Allowed";
        case HttpURLConnection.HTTP_NOT_ACCEPTABLE: return "Not Acceptable";
        case HttpURLConnection.HTTP_PROXY_AUTH: return "Proxy Authentication Required";
        case HttpURLConnection.HTTP_CLIENT_TIMEOUT: return "Request Time-Out";
        case HttpURLConnection.HTTP_CONFLICT: return "Conflict";
        case HttpURLConnection.HTTP_GONE: return "Gone";
        case HttpURLConnection.HTTP_LENGTH_REQUIRED: return "Length Required";
        case HttpURLConnection.HTTP_PRECON_FAILED: return "Precondition Failed";
        case HttpURLConnection.HTTP_ENTITY_TOO_LARGE: return "Request Entity Too Large";
        case HttpURLConnection.HTTP_REQ_TOO_LONG: return "Request-URI Too Large";
        case HttpURLConnection.HTTP_UNSUPPORTED_TYPE: return "Unsupported Media Type";

        // 5xx
        case HttpURLConnection.HTTP_INTERNAL_ERROR: return "Internal Server Error";
        case HttpURLConnection.HTTP_NOT_IMPLEMENTED: return "Not Implemented";
        case HttpURLConnection.HTTP_BAD_GATEWAY: return "Bad Gateway";
        case HttpURLConnection.HTTP_UNAVAILABLE: return "Service Unavailable";
        case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: return "Gateway Timeout";
        case HttpURLConnection.HTTP_VERSION: return "Version Not Supported";

        default: return "unknown";
    }
}
 
源代码14 项目: commerce-gradle-plugin   文件: HttpUtils.java
private static boolean isRedirect(HttpURLConnection connection) throws Exception {
    return connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM ||
            connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP ||
            connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER;
}
 
源代码15 项目: cxf   文件: HTTPConduit.java
protected void handleHttpRetryException(HttpRetryException e) throws IOException {
    String msg = "HTTP response '" + e.responseCode() + ": "
        + getResponseMessage() + "' invoking " + url;
    switch (e.responseCode()) {
    case HttpURLConnection.HTTP_MOVED_PERM: // 301
    case HttpURLConnection.HTTP_MOVED_TEMP: // 302
    case HttpURLConnection.HTTP_SEE_OTHER:  // 303
    case 307:
        msg += " that returned location header '" + e.getLocation() + "'";
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED: // 401
        if (authorizationPolicy == null || authorizationPolicy.getUserName() == null) {
            msg += " with NO authorization username configured in conduit " + getConduitName();
        } else {
            msg += " with authorization username '" + authorizationPolicy.getUserName() + "'";
        }
        break;
    case HttpURLConnection.HTTP_PROXY_AUTH: // 407
        if (proxyAuthorizationPolicy == null || proxyAuthorizationPolicy.getUserName() == null) {
            msg += " with NO proxy authorization configured in conduit " + getConduitName();
        } else {
            msg += " with proxy authorization username '"
                + proxyAuthorizationPolicy.getUserName() + "'";
        }
        if (clientSidePolicy == null || clientSidePolicy.getProxyServer() == null) {
            if (usingProxy()) {
                msg += " using a proxy even if NONE is configured in CXF conduit "
                    + getConduitName()
                    + " (maybe one is configured by java.net.ProxySelector)";
            } else {
                msg += " but NO proxy was used by the connection (none configured in cxf "
                    + "conduit and none selected by java.net.ProxySelector)";
            }
        } else {
            msg += " using " + clientSidePolicy.getProxyServerType() + " proxy "
                + clientSidePolicy.getProxyServer() + ":"
                + clientSidePolicy.getProxyServerPort();
        }
        break;
    default:
        // No other type of HttpRetryException should be thrown
        break;
    }
    throw new IOException(msg, e);
}
 
源代码16 项目: jeka   文件: IvyFollowRedirectUrlHandler.java
private boolean checkRedirect(HttpURLConnection con) throws IOException {
    final int status = con.getResponseCode();
    return status == HttpURLConnection.HTTP_MOVED_TEMP
            || status == HttpURLConnection.HTTP_MOVED_PERM
            || status == HttpURLConnection.HTTP_SEE_OTHER;
}
 
源代码17 项目: Elasticsearch   文件: HttpDownloadHelper.java
private URLConnection openConnection(URL aSource) throws IOException {

            // set up the URL connection
            URLConnection connection = aSource.openConnection();
            // modify the headers
            // NB: things like user authentication could go in here too.
            if (hasTimestamp) {
                connection.setIfModifiedSince(timestamp);
            }

            // in case the plugin manager is its own project, this can become an authenticator
            boolean isSecureProcotol = "https".equalsIgnoreCase(aSource.getProtocol());
            boolean isAuthInfoSet = !Strings.isNullOrEmpty(aSource.getUserInfo());
            if (isAuthInfoSet) {
                if (!isSecureProcotol) {
                    throw new IOException("Basic auth is only supported for HTTPS!");
                }
                String basicAuth = Base64.encodeBytes(aSource.getUserInfo().getBytes(StandardCharsets.UTF_8));
                connection.setRequestProperty("Authorization", "Basic " + basicAuth);
            }

            if (connection instanceof HttpURLConnection) {
                ((HttpURLConnection) connection).setInstanceFollowRedirects(false);
                connection.setUseCaches(true);
                connection.setConnectTimeout(5000);
            }
            connection.setRequestProperty("ES-Version", Version.CURRENT.toString());
            connection.setRequestProperty("ES-Build-Hash", Build.CURRENT.hashShort());
            connection.setRequestProperty("User-Agent", "elasticsearch-plugin-manager");

            // connect to the remote site (may take some time)
            connection.connect();

            // First check on a 301 / 302 (moved) response (HTTP only)
            if (connection instanceof HttpURLConnection) {
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                int responseCode = httpConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_MOVED_PERM ||
                        responseCode == HttpURLConnection.HTTP_MOVED_TEMP ||
                        responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
                    String newLocation = httpConnection.getHeaderField("Location");
                    URL newURL = new URL(newLocation);
                    if (!redirectionAllowed(aSource, newURL)) {
                        return null;
                    }
                    return openConnection(newURL);
                }
                // next test for a 304 result (HTTP only)
                long lastModified = httpConnection.getLastModified();
                if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED
                        || (lastModified != 0 && hasTimestamp && timestamp >= lastModified)) {
                    // not modified so no file download. just return
                    // instead and trace out something so the user
                    // doesn't think that the download happened when it
                    // didn't
                    return null;
                }
                // test for 401 result (HTTP only)
                if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    String message = "HTTP Authorization failure";
                    throw new IOException(message);
                }
            }

            //REVISIT: at this point even non HTTP connections may
            //support the if-modified-since behaviour -we just check
            //the date of the content and skip the write if it is not
            //newer. Some protocols (FTP) don't include dates, of
            //course.
            return connection;
        }
 
源代码18 项目: K-Sonic   文件: 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 项目: stendhal   文件: HttpClient.java
/**
 * Determine if a repsonse code is a redirect
 *
 * @param responseCode
 * @return
 */
private boolean isRedirect(int responseCode) {
	return responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER;
}
 
源代码20 项目: takes   文件: RsForward.java
/**
 * Ctor.
 * @param res Original response
 * @param loc Location
 */
public RsForward(final Response res, final CharSequence loc) {
    this(res, HttpURLConnection.HTTP_SEE_OTHER, loc);
}