本文整理了Java中java.net.HttpURLConnection.setInstanceFollowRedirects()
方法的一些代码示例,展示了HttpURLConnection.setInstanceFollowRedirects()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpURLConnection.setInstanceFollowRedirects()
方法的具体详情如下:
包路径:java.net.HttpURLConnection
类名称:HttpURLConnection
方法名:setInstanceFollowRedirects
[英]Sets whether this connection follows redirects.
[中]设置此连接是否遵循重定向。
代码示例来源:origin: stackoverflow.com
String urlParameters = "param1=a¶m2=b¶m3=c";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "http://example.com/index.php";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write( postData );
}
代码示例来源:origin: spring-projects/spring-framework
/**
* Template method for preparing the given {@link HttpURLConnection}.
* <p>The default implementation prepares the connection for input and output, and sets the HTTP method.
* @param connection the connection to prepare
* @param httpMethod the HTTP request method ({@code GET}, {@code POST}, etc.)
* @throws IOException in case of I/O errors
*/
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
if (this.connectTimeout >= 0) {
connection.setConnectTimeout(this.connectTimeout);
}
if (this.readTimeout >= 0) {
connection.setReadTimeout(this.readTimeout);
}
connection.setDoInput(true);
if ("GET".equals(httpMethod)) {
connection.setInstanceFollowRedirects(true);
}
else {
connection.setInstanceFollowRedirects(false);
}
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) ||
"PATCH".equals(httpMethod) || "DELETE".equals(httpMethod)) {
connection.setDoOutput(true);
}
else {
connection.setDoOutput(false);
}
connection.setRequestMethod(httpMethod);
}
代码示例来源:origin: stackoverflow.com
URL url = new URL(url);
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
URLConnection conn = secondURL.openConnection();
代码示例来源:origin: Atmosphere/atmosphere
public void request(String urlString) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(urlString);
urlConnection = openURLConnection(url);
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setRequestMethod(GET_METHOD_NAME);
urlConnection.setRequestProperty("User-agent", uaName + " (" + osString + ")");
logger.debug("Sending Server's information to Atmosphere's Google Analytics {} {}", urlString, uaName + " (" + osString + ")");
urlConnection.connect();
int responseCode = getResponseCode(urlConnection);
if (responseCode != HttpURLConnection.HTTP_OK) {
logError("JGoogleAnalytics: Error tracking, url=" + urlString);
} else {
logMessage(SUCCESS_MESSAGE);
}
} catch (Exception e) {
logError(e.getMessage());
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
代码示例来源:origin: bumptech/glide
urlConnection.setInstanceFollowRedirects(false);
return null;
final int statusCode = urlConnection.getResponseCode();
if (isHttpOk(statusCode)) {
return getStreamForSuccessfulRequest(urlConnection);
throw new HttpException("Received empty or null redirect url");
URL redirectUrl = new URL(url, redirectUrlString);
代码示例来源:origin: google/ExoPlayer
boolean followRedirects)
throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(connectTimeoutMillis);
connection.setReadTimeout(readTimeoutMillis);
connection.setRequestProperty("Accept-Encoding", "identity");
connection.setInstanceFollowRedirects(followRedirects);
connection.setDoOutput(httpBody != null);
connection.setRequestMethod(DataSpec.getStringForHttpMethod(httpMethod));
if (httpBody != null) {
connection.setFixedLengthStreamingMode(httpBody.length);
代码示例来源:origin: spotify/helios
private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
final Map<String, List<String>> headers,
final String endpointHost)
throws IOException {
if (log.isTraceEnabled()) {
log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
Joiner.on(',').withKeyValueSeparator("=").join(headers),
entity.length, Json.asPrettyStringUnchecked(entity));
} else {
log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
}
final HttpURLConnection connection = (HttpURLConnection) ipUri.toURL().openConnection();
handleHttps(connection, endpointHost, hostnameVerifierProvider, extraHttpsHandler);
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(httpTimeoutMillis);
connection.setReadTimeout(httpTimeoutMillis);
for (final Map.Entry<String, List<String>> header : headers.entrySet()) {
for (final String value : header.getValue()) {
connection.addRequestProperty(header.getKey(), value);
}
}
if (entity.length > 0) {
connection.setDoOutput(true);
connection.getOutputStream().write(entity);
}
setRequestMethod(connection, method, connection instanceof HttpsURLConnection);
return connection;
}
代码示例来源:origin: jMonkeyEngine/jmonkeyengine
private InputStream readData(int offset, int length) throws IOException{
HttpURLConnection conn = (HttpURLConnection) zipUrl.openConnection();
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(false);
String range = "-";
if (offset != Integer.MAX_VALUE){
range = offset + range;
}
if (length != Integer.MAX_VALUE){
if (offset != Integer.MAX_VALUE){
range = range + (offset + length - 1);
}else{
range = range + length;
}
}
conn.setRequestProperty("Range", "bytes=" + range);
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_PARTIAL){
return conn.getInputStream();
}else if (conn.getResponseCode() == HttpURLConnection.HTTP_OK){
throw new IOException("Your server does not support HTTP feature Content-Range. Please contact your server administrator.");
}else{
throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage());
}
}
代码示例来源:origin: google/agera
@NonNull
private HttpResponse getHttpResponseResult(final @NonNull HttpRequest request,
@NonNull final HttpURLConnection connection) throws IOException {
connection.setConnectTimeout(request.connectTimeoutMs);
connection.setReadTimeout(request.readTimeoutMs);
connection.setInstanceFollowRedirects(request.followRedirects);
connection.setUseCaches(request.useCaches);
connection.setDoInput(true);
connection.setRequestMethod(request.method);
for (final Entry<String, String> headerField : request.header.entrySet()) {
connection.addRequestProperty(headerField.getKey(), headerField.getValue());
}
final byte[] body = request.body;
if (body.length > 0) {
connection.setDoOutput(true);
final OutputStream out = connection.getOutputStream();
try {
out.write(body);
} finally {
out.close();
}
}
final String responseMessage = connection.getResponseMessage();
return httpResponse(connection.getResponseCode(),
responseMessage != null ? responseMessage : "",
getHeader(connection), getByteArray(connection));
}
代码示例来源:origin: stackoverflow.com
HttpURLConnection con = (HttpURLConnection)(new URL( url ).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
int responseCode = con.getResponseCode();
System.out.println( responseCode );
String location = con.getHeaderField( "Location" );
System.out.println( location );
代码示例来源:origin: pwittchen/ReactiveNetwork
protected HttpURLConnection createHttpUrlConnection(final String host, final int port,
final int timeoutInMs) throws IOException {
URL initialUrl = new URL(host);
URL url = new URL(initialUrl.getProtocol(), initialUrl.getHost(), port, initialUrl.getFile());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(timeoutInMs);
urlConnection.setReadTimeout(timeoutInMs);
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setUseCaches(false);
return urlConnection;
}
}
代码示例来源:origin: yanzhenjie/NoHttp
@Override
public Network execute(BasicRequest<?> request) throws Exception {
URL url = new URL(request.url());
HttpURLConnection connection = URLConnectionFactory.getInstance().open(url, request.getProxy());
connection.setConnectTimeout(request.getConnectTimeout());
connection.setReadTimeout(request.getReadTimeout());
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod(request.getRequestMethod().getValue());
代码示例来源:origin: nutzam/nutz
conn = (HttpURLConnection) request.getUrl().openConnection(proxy);
conn.setConnectTimeout(connTime);
conn.setInstanceFollowRedirects(followRedirects);
if (timeout > 0)
conn.setReadTimeout(timeout);
conn = (HttpURLConnection) url.openConnection();
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection httpsc = (HttpsURLConnection)conn;
conn.setRequestMethod(request.getMethod().name());
else
conn.setRequestMethod(request.getMethodString());
if (timeout > 0)
conn.setReadTimeout(timeout);
else
conn.setReadTimeout(Default_Read_Timeout);
conn.setInstanceFollowRedirects(followRedirects);
if (interceptor != null)
this.interceptor.afterConnect(request, conn);
代码示例来源:origin: Justson/AgentWeb
private HttpURLConnection createUrlConnectionAndSettingHeaders(URL url) throws IOException {
HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();
mHttpURLConnection.setConnectTimeout(mConnectTimeOut);
mHttpURLConnection.setInstanceFollowRedirects(false);
mHttpURLConnection.setReadTimeout(mDownloadTask.getBlockMaxTime());
mHttpURLConnection.setRequestProperty("Accept", "application/*");
mHttpURLConnection.setRequestProperty("Accept-Encoding", "identity");
mHttpURLConnection.setRequestProperty("Connection", "close");
mHttpURLConnection.setRequestProperty("Cookie", AgentWebConfig.getCookiesByUrl(url.toString()));
Map<String, String> mHeaders = null;
if ((null != mDownloadTask.getExtraServiceImpl()) && null != (mHeaders = mDownloadTask.getExtraServiceImpl().getHeaders()) &&
!mHeaders.isEmpty()) {
for (Map.Entry<String, String> entry : mHeaders.entrySet()) {
if (TextUtils.isEmpty(entry.getKey()) || TextUtils.isEmpty(entry.getValue())) {
continue;
}
mHttpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
if (mDownloadTask.getFile().length() > 0) {
String mEtag = "";
if (!TextUtils.isEmpty((mEtag = getEtag()))) {
LogUtils.i(TAG, "Etag:" + mEtag);
mHttpURLConnection.setRequestProperty("If-Match", getEtag());
}
mHttpURLConnection.setRequestProperty("Range", "bytes=" + (mLastLoaded = mDownloadTask.getFile().length()) + "-");
}
return mHttpURLConnection;
}
代码示例来源:origin: jersey/jersey
setRequestMethodViaJreBugWorkaround(uc, httpMethod);
} else {
uc.setRequestMethod(httpMethod);
uc.setInstanceFollowRedirects(request.resolveProperty(ClientProperties.FOLLOW_REDIRECTS, true));
final int code = uc.getResponseCode();
final String reasonPhrase = uc.getResponseMessage();
final Response.StatusType status =
代码示例来源:origin: org.springframework/spring-web
/**
* Template method for preparing the given {@link HttpURLConnection}.
* <p>The default implementation prepares the connection for input and output, and sets the HTTP method.
* @param connection the connection to prepare
* @param httpMethod the HTTP request method ({@code GET}, {@code POST}, etc.)
* @throws IOException in case of I/O errors
*/
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
if (this.connectTimeout >= 0) {
connection.setConnectTimeout(this.connectTimeout);
}
if (this.readTimeout >= 0) {
connection.setReadTimeout(this.readTimeout);
}
connection.setDoInput(true);
if ("GET".equals(httpMethod)) {
connection.setInstanceFollowRedirects(true);
}
else {
connection.setInstanceFollowRedirects(false);
}
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) ||
"PATCH".equals(httpMethod) || "DELETE".equals(httpMethod)) {
connection.setDoOutput(true);
}
else {
connection.setDoOutput(false);
}
connection.setRequestMethod(httpMethod);
}
代码示例来源:origin: stackoverflow.com
private void updateCustomer(Customer customer) {
try {
URL url = new URL("http://www.example.com/customers");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
jaxbContext.createMarshaller().marshal(customer, os);
os.flush();
connection.getResponseCode();
connection.disconnect();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
代码示例来源:origin: TeamNewPipe/NewPipe
/**
* Open connection
*
* @param threadId id of the calling thread, used only for debug
* @param rangeStart range start
* @param rangeEnd range end
* @return a {@link java.net.URLConnection URLConnection} linking to the URL.
* @throws IOException if an I/O exception occurs.
*/
HttpURLConnection openConnection(int threadId, long rangeStart, long rangeEnd) throws IOException {
URL url = new URL(urls[current]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(true);
if (rangeStart >= 0) {
String req = "bytes=" + rangeStart + "-";
if (rangeEnd > 0) req += rangeEnd;
conn.setRequestProperty("Range", req);
if (DEBUG) {
Log.d(TAG, threadId + ":" + conn.getRequestProperty("Range"));
}
}
return conn;
}
代码示例来源:origin: org.jsoup/jsoup
private static HttpURLConnection createConnection(Connection.Request req) throws IOException {
final HttpURLConnection conn = (HttpURLConnection) (
req.proxy() == null ?
req.url().openConnection() :
req.url().openConnection(req.proxy())
);
conn.setRequestMethod(req.method().name());
conn.setInstanceFollowRedirects(false); // don't rely on native redirection support
conn.setConnectTimeout(req.timeout());
conn.setReadTimeout(req.timeout() / 2); // gets reduced after connection is made and status is read
代码示例来源:origin: Atmosphere/atmosphere
logger.debug("Retrieving Atmosphere's latest version from http://async-io.org/version.html");
HttpURLConnection urlConnection = (HttpURLConnection)
URI.create("http://async-io.org/version.html").toURL().openConnection();
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
urlConnection.setRequestProperty("Connection", "keep-alive");
urlConnection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
urlConnection.setRequestProperty("If-Modified-Since", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
urlConnection.setInstanceFollowRedirects(true);
内容来源于网络,如有侵权,请联系作者删除!