当前位置: 首页>>代码示例>>Java>>正文


Java HttpURLConnection.setInstanceFollowRedirects方法代码示例

本文整理汇总了Java中java.net.HttpURLConnection.setInstanceFollowRedirects方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.setInstanceFollowRedirects方法的具体用法?Java HttpURLConnection.setInstanceFollowRedirects怎么用?Java HttpURLConnection.setInstanceFollowRedirects使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.net.HttpURLConnection的用法示例。


在下文中一共展示了HttpURLConnection.setInstanceFollowRedirects方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testDisableRedirectsTryReadBody

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@SmallTest
@Feature({"Cronet"})
@OnlyRunCronetHttpURLConnection
// Cronet does not support reading response body of a 302 response.
public void testDisableRedirectsTryReadBody() throws Exception {
    URL url = new URL(NativeTestServer.getFileURL("/redirect.html"));
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setInstanceFollowRedirects(false);
    try {
        connection.getInputStream();
        fail();
    } catch (IOException e) {
        // Expected.
    }
    assertNull(connection.getErrorStream());
    connection.disconnect();
}
 
开发者ID:lizhangqu,项目名称:chromium-net-for-android,代码行数:19,代码来源:CronetHttpURLConnectionTest.java

示例2: setInstanceFollowRedirectsFalse

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Test
public void setInstanceFollowRedirectsFalse() throws Exception {
  server.enqueue(new MockResponse()
      .setResponseCode(302)
      .addHeader("Location: /b")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  HttpURLConnection connection = factory.open(server.url("/a").url());
  connection.setInstanceFollowRedirects(false);
  assertResponseBody(connection, "A");
  assertResponseCode(connection, 302);
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:15,代码来源:OkUrlFactoryTest.java

示例3: downloadViaHttp

import java.net.HttpURLConnection; //导入方法依赖的package包/类
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");
}
 
开发者ID:xiong-it,项目名称:ZXingAndroidExt,代码行数:32,代码来源:HttpHelper.java

示例4: asyncCheckLatestAppVersion

import java.net.HttpURLConnection; //导入方法依赖的package包/类
private void asyncCheckLatestAppVersion() {
    try {
        URL url = new URL(getString(R.string.latest_release_url));
        HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
        ucon.setInstanceFollowRedirects(false);
        URL secondURL = new URL(ucon.getHeaderField("Location"));
        String secondUrl = String.valueOf(secondURL);
        String latestVersion = Uri.parse(secondUrl).getLastPathSegment();
        Log.d("GM/updateUrl", secondUrl);
        if (getActivity() != null) {
            String checkUrl = getString(R.string.current_release_url_prefix) + BuildConfig.VERSION_NAME;
            if (secondUrl.equals(checkUrl)) {
                versionSummary = BuildConfig.VERSION_NAME + " " +
                        getString(R.string.version_summary_latest);
            } else {
                versionSummary = BuildConfig.VERSION_NAME + " " +
                        "(" + getString(R.string.version_summary_changed_latest) + latestVersion + ")";
                latestVersionUrl = secondUrl;
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    versionPref.setSummary(versionSummary);
                    Log.d("GM/versionChecked", versionSummary);
                }
            });
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
开发者ID:xRahul,项目名称:GroupingMessages,代码行数:32,代码来源:SettingsFragment.java

示例5: downloadViaHttp

import java.net.HttpURLConnection; //导入方法依赖的package包/类
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");
}
 
开发者ID:amap-demo,项目名称:weex-3d-map,代码行数:32,代码来源:HttpHelper.java

示例6: fetchRedirect

import java.net.HttpURLConnection; //导入方法依赖的package包/类
private List<String> fetchRedirect(String url, List<String> redirects) throws IOException {
    redirects.add(url);

    HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    con.setInstanceFollowRedirects(false);
    con.connect();

    if (con.getHeaderField("Location") == null) {
        return redirects;
    }
    return fetchRedirect(con.getHeaderField("Location"), redirects);
}
 
开发者ID:avaire,项目名称:avaire,代码行数:15,代码来源:ExpandUrlCommand.java

示例7: makeConnection

import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
 * Configures a connection and opens it.
 *
 * @param url The url to connect to.
 * @param postBody The body data for a POST request.
 * @param position The byte offset of the requested data.
 * @param length The length of the requested data, or {@link C#LENGTH_UNBOUNDED}.
 * @param allowGzip Whether to allow the use of gzip.
 * @param followRedirects Whether to follow redirects.
 */
private HttpURLConnection makeConnection(URL url, byte[] postBody, long position,
    long length, boolean allowGzip, boolean followRedirects) throws IOException {
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setConnectTimeout(connectTimeoutMillis);
  connection.setReadTimeout(readTimeoutMillis);
  synchronized (requestProperties) {
    for (Map.Entry<String, String> property : requestProperties.entrySet()) {
      connection.setRequestProperty(property.getKey(), property.getValue());
    }
  }
  if (!(position == 0 && length == C.LENGTH_UNBOUNDED)) {
    String rangeRequest = "bytes=" + position + "-";
    if (length != C.LENGTH_UNBOUNDED) {
      rangeRequest += (position + length - 1);
    }
    connection.setRequestProperty("Range", rangeRequest);
  }
  connection.setRequestProperty("User-Agent", userAgent);
  if (!allowGzip) {
    connection.setRequestProperty("Accept-Encoding", "identity");
  }
  connection.setInstanceFollowRedirects(followRedirects);
  connection.setDoOutput(postBody != null);
  if (postBody != null) {
    connection.setFixedLengthStreamingMode(postBody.length);
    connection.connect();
    OutputStream os = connection.getOutputStream();
    os.write(postBody);
    os.close();
  } else {
    connection.connect();
  }
  return connection;
}
 
开发者ID:MLNO,项目名称:airgram,代码行数:45,代码来源:DefaultHttpDataSource.java

示例8: createConnection

import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
 * Create an {@link HttpURLConnection} for the specified {@code url}.
 */
protected HttpURLConnection createConnection(URL url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Workaround for the M release HttpURLConnection not observing the
    // HttpURLConnection.setFollowRedirects() property.
    // https://code.google.com/p/android/issues/detail?id=194495
    connection.setInstanceFollowRedirects(HttpURLConnection.getFollowRedirects());

    return connection;
}
 
开发者ID:Ace201m,项目名称:Codeforces,代码行数:14,代码来源:HurlStack.java

示例9: prepareConnection

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod)
        throws IOException {
    super.prepareConnection(connection, httpMethod);
    connection.setInstanceFollowRedirects(false);
    connection.setUseCaches(false);
}
 
开发者ID:GoldRenard,项目名称:JuniperBotJ,代码行数:8,代码来源:DiscordHttpRequestFactory.java

示例10: connectToEndpoint

import java.net.HttpURLConnection; //导入方法依赖的package包/类
public HttpURLConnection connectToEndpoint(URI endpoint, Map<String, String> headers) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) endpoint.toURL().openConnection(Proxy.NO_PROXY);
    connection.setConnectTimeout(1000 * 2);
    connection.setReadTimeout(1000 * 5);
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    headers.forEach(connection::addRequestProperty);
    connection.setInstanceFollowRedirects(false);
    connection.connect();

    return connection;
}
 
开发者ID:aws,项目名称:aws-sdk-java-v2,代码行数:13,代码来源:ConnectionUtils.java

示例11: getBitmap

import java.net.HttpURLConnection; //导入方法依赖的package包/类
private Bitmap getBitmap(String url) {
    File f = fileCache.getFile(url);

    //from SD cache
    Bitmap b = decodeFile(f);
    if (b != null) {
        return b;
    }

    //from web
    try {
        Bitmap bitmap;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is = conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Throwable ex) {
        ex.printStackTrace();
        if (ex instanceof OutOfMemoryError) {
            memoryCache.clear();
        }
        return null;
    }
}
 
开发者ID:sega4revenge,项目名称:Sega,代码行数:32,代码来源:ImageLoader.java

示例12: fastConfigureConnection

import java.net.HttpURLConnection; //导入方法依赖的package包/类
private static HttpURLConnection fastConfigureConnection(HttpURLConnection http) {
	http.addRequestProperty("User-Agent",
			"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0 VkAuthLib/0.0.1 VkAccess/0.0.1");
	http.addRequestProperty("Accept-Language", "ru-ru,ru;q=0.5");
	http.setInstanceFollowRedirects(true);
	http.setDoInput(true);
	http.setDoOutput(true);
	return http;
}
 
开发者ID:Ivan-Alone,项目名称:VkAccess,代码行数:10,代码来源:VkAccess.java

示例13: create

import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
 * <b>CREATE</b>
 *
 * curl -i -X PUT "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=CREATE
 * [&overwrite=<true|false>][&blocksize=<LONG>][&replication=<SHORT>]
 * [&permission=<OCTAL>][&buffersize=<INT>]"
 *
 * @param path
 * @param is
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String create(String path, InputStream is)
        throws MalformedURLException, IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();

    String redirectUrl = null;
    HttpURLConnection conn = authenticatedURL
            .openConnection(
                    new URL(new URL(httpfsUrl), MessageFormat.format(
                            "/webhdfs/v1/{0}?op=CREATE",
                            URLUtil.encodePath(path))), token);
    conn.setRequestMethod("PUT");
    conn.setInstanceFollowRedirects(false);
    conn.connect();
    logger.info("Location:" + conn.getHeaderField("Location"));
    System.out.println("Location:" + conn.getHeaderField("Location"));
    resp = result(conn, true);
    if (conn.getResponseCode() == 307)
        redirectUrl = conn.getHeaderField("Location");
    conn.disconnect();

    if (redirectUrl != null) {
        conn = authenticatedURL.openConnection(new URL(redirectUrl), token);
        conn.setRequestMethod("PUT");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/octet-stream");
        // conn.setRequestProperty("Transfer-Encoding", "chunked");
        final int _SIZE = is.available();
        conn.setRequestProperty("Content-Length", "" + _SIZE);
        conn.setFixedLengthStreamingMode(_SIZE);
        conn.connect();
        OutputStream os = conn.getOutputStream();
        copy(is, os);
        // Util.copyStream(is, os);
        is.close();
        os.close();
        resp = result(conn, false);
        conn.disconnect();
    }

    return resp;
}
 
开发者ID:Transwarp-DE,项目名称:Transwarp-Sample-Code,代码行数:59,代码来源:KerberosWebHDFSConnection2.java

示例14: getResponse

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Override
public ResponseScriptType getResponse(boolean isGET)
{
	try
	{
		final String data = getFormData();

		String extra = "";
		if( isGET && !Check.isEmpty(data) )
		{
			String qs = url.getQuery();
			if( Check.isEmpty(qs) )
			{
				extra += "?" + data;
			}
			else
			{
				extra += "?" + qs + "&" + data;
			}
		}
		final String urlString = url.toString() + extra;

		final URL finalUrl = new URL(urlString);
		final HttpURLConnection conn = (HttpURLConnection) finalUrl.openConnection();

		conn.setRequestMethod(isGET ? "GET" : "POST");
		conn.setAllowUserInteraction(false);
		conn.setInstanceFollowRedirects(true);

		conn.setDoOutput(true);
		conn.setDoInput(true);

		// Send data
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Accept", "*/*");

		if( !isGET )
		{
			try( Writer wr = new OutputStreamWriter(conn.getOutputStream()) )
			{
				if( !isGET )
				{
					wr.write(data);
				}
				wr.flush();
			}
		}

		// Get the response
		final String contentType = conn.getContentType();

		try( InputStream is = conn.getInputStream() )
		{
			if( contentType == null || contentType.startsWith("text/") )
			{
				Reader rd = new InputStreamReader(is);
				StringWriter sw = new StringWriter();
				CharStreams.copy(rd, sw);
				return new ResponseScriptTypeImpl(sw.toString(), conn.getResponseCode(), contentType);
			}
			else
			{
				ByteArrayOutputStream os = new ByteArrayOutputStream();
				ByteStreams.copy(is, os);
				return new ResponseScriptTypeImpl(os.toByteArray(), conn.getResponseCode(), contentType);
			}
		}
	}
	catch( IOException e )
	{
		return new ResponseScriptTypeImpl("ERROR: " + e.getMessage(), 400, "text/plain");
	}
}
 
开发者ID:equella,项目名称:Equella,代码行数:74,代码来源:UtilsScriptWrapper.java

示例15: append

import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
 * curl -i -X POST
 * "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=APPEND[&buffersize=<INT>]"
 *
 * @param path
 * @param is
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String append(String path, InputStream is)
        throws  IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();
    String spec = MessageFormat.format(
            "/webhdfs/v1/{0}?op=APPEND&user.name={1}",
            URLUtil.encodePath(path), this.principal);
    String redirectUrl = null;
    HttpURLConnection conn = authenticatedURL.openConnection(new URL(
            new URL(httpfsUrl), spec), token);
    conn.setRequestMethod("POST");
    conn.setInstanceFollowRedirects(false);
    conn.connect();
    logger.info("Location:" + conn.getHeaderField("Location"));
    resp = result(conn, true);
    if (conn.getResponseCode() == 307)
        redirectUrl = conn.getHeaderField("Location");
    conn.disconnect();

    if (redirectUrl != null) {
        conn = authenticatedURL.openConnection(new URL(redirectUrl), token);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/octet-stream");
        // conn.setRequestProperty("Transfer-Encoding", "chunked");
        final int _SIZE = is.available();
        conn.setRequestProperty("Content-Length", "" + _SIZE);
        conn.setFixedLengthStreamingMode(_SIZE);
        conn.connect();
        OutputStream os = conn.getOutputStream();
        copy(is, os);
        // Util.copyStream(is, os);
        is.close();
        os.close();
        resp = result(conn, true);
        conn.disconnect();
    }

    return resp;
}
 
开发者ID:Transwarp-DE,项目名称:Transwarp-Sample-Code,代码行数:54,代码来源:PseudoWebHDFSConnection.java


注:本文中的java.net.HttpURLConnection.setInstanceFollowRedirects方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。