本文整理汇总了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();
}
示例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);
}
示例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");
}
示例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();
}
}
示例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");
}
示例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);
}
示例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;
}
示例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;
}
示例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);
}
示例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;
}
示例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;
}
}
示例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;
}
示例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;
}
示例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");
}
}
示例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;
}