Java Code Examples for java.net.HttpURLConnection#setInstanceFollowRedirects()

The following examples show how to use java.net.HttpURLConnection#setInstanceFollowRedirects() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JGoogleAnalyticsTracker.java    From ForgeWurst with GNU General Public License v3.0 6 votes vote down vote up
private static void dispatchRequest(String argURL, String userAgent)
{
	try
	{
		URL url = new URL(argURL);
		HttpURLConnection connection =
			(HttpURLConnection)url.openConnection(proxy);
		connection.setRequestMethod("GET");
		connection.setInstanceFollowRedirects(true);
		if(userAgent != null)
			connection.addRequestProperty("User-Agent", userAgent);
		connection.connect();
		int responseCode = connection.getResponseCode();
		if(responseCode != HttpURLConnection.HTTP_OK)
			logger.log(Level.SEVERE,
				"JGoogleAnalyticsTracker: Error requesting url '" + argURL
					+ "', received response code " + responseCode);
		else
			logger.log(Level.CONFIG,
				"JGoogleAnalyticsTracker: Tracking success for url '"
					+ argURL + "'");
	}catch(Exception e)
	{
		logger.log(Level.SEVERE, "Error making tracking request", e);
	}
}
 
Example 2
Source File: DefaultModelResolver.java    From migration-tooling with Apache License 2.0 6 votes vote down vote up
private boolean pomFileExists(URL url) {
  try {
    URLConnection urlConnection = url.openConnection();
    if (!(urlConnection instanceof HttpURLConnection)) {
      return false;
    }

    HttpURLConnection connection = (HttpURLConnection) urlConnection;
    connection.setRequestMethod("HEAD");
    connection.setInstanceFollowRedirects(true);
    connection.connect();

    int code = connection.getResponseCode();
    if (code == 200) {
      return true;
    }
  } catch (IOException e) {
    // Something went wrong, fall through.
  }
  return false;
}
 
Example 3
Source File: GettUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
public static void setHttpHeader() {

        try {
            uc = (HttpURLConnection) u.openConnection();
            uc.setDoOutput(true);
            uc.setRequestProperty("Host", "www.ge.tt");
            uc.setRequestProperty("Connection", "keep-alive");
            uc.setRequestProperty("Referer", "http://www.ge.tt/");
            uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1");
            uc.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            uc.setRequestProperty("Accept-Encoding", "html");
            uc.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
            uc.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
            uc.setRequestProperty("Content-Type", "application/xml");
            uc.setRequestMethod("POST");
            uc.setInstanceFollowRedirects(false);


        } catch (Exception e) {
            System.out.println("ex" + e.toString());
        }
    }
 
Example 4
Source File: RequestMappingViewResolutionIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-15291
public void redirect() throws Exception {
	SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory() {
		@Override
		protected void prepareConnection(HttpURLConnection conn, String method) throws IOException {
			super.prepareConnection(conn, method);
			conn.setInstanceFollowRedirects(false);
		}
	};

	URI uri = new URI("http://localhost:" + this.port + "/redirect");
	RequestEntity<Void> request = RequestEntity.get(uri).accept(MediaType.ALL).build();
	ResponseEntity<Void> response = new RestTemplate(factory).exchange(request, Void.class);

	assertEquals(HttpStatus.SEE_OTHER, response.getStatusCode());
	assertEquals("/", response.getHeaders().getLocation().toString());
}
 
Example 5
Source File: UrlUtil.java    From materialup with Apache License 2.0 6 votes vote down vote up
public static String getFinalURL(String url) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
    con.setInstanceFollowRedirects(false);
    con.connect();
    con.getInputStream();

    if (con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || con.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
        String redirectUrl = con.getHeaderField("Location");
        if (TextUtils.isEmpty(redirectUrl)) {
            return url;
        }
        if (redirectUrl.startsWith(Api.getEndpoint())) {
            return getFinalURL(redirectUrl);
        }
        return redirectUrl;
    }
    return url;
}
 
Example 6
Source File: HttpHelper.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
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();
  }
}
 
Example 7
Source File: WebConsoleRedirectionTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private HttpURLConnection getConnection() throws Exception {
    final URL url = new URL("http://" + TestSuiteEnvironment.getServerAddress() + ":" + TestSuiteEnvironment.getServerPort() + "/");
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    assertNotNull(connection);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod(HttpGet.METHOD_NAME);
    connection.connect();
    return connection;
}
 
Example 8
Source File: HttpHelper.java    From ZXing-Orient with Apache License 2.0 5 votes vote down vote up
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();
  }
}
 
Example 9
Source File: ChannelServiceHttpClient.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@NonNull
private HttpURLConnection openGetConnection(@NonNull Uri uri) throws IOException {
    HttpURLConnection conn = openHttpConnection(uri);
    conn.setInstanceFollowRedirects(true);
    conn.setRequestProperty("User-Agent", userAgentGenerator.getUserAgent());
    conn.setRequestProperty("Accept-Encoding", "gzip");
    conn.setConnectTimeout(connectTimeoutMillis);
    conn.setReadTimeout(readTimeoutMillis);
    conn.setRequestMethod(HttpMethod.GET.name());
    return conn;
}
 
Example 10
Source File: Updater.java    From YalpStore with GNU General Public License v2.0 5 votes vote down vote up
private boolean isAvailable(int versionCode) {
    try {
        URL url = getUrl(versionCode);
        if (null == url) {
            return false;
        }
        HttpURLConnection connection = NetworkUtil.getHttpURLConnection(url);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("HEAD");
        return connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST;
    } catch (IOException x) {
        return false;
    }
}
 
Example 11
Source File: Util.java    From Leanplum-Android-SDK with Apache License 2.0 5 votes vote down vote up
static HttpURLConnection createHttpUrlConnection(
    String fullPath, String httpMethod, boolean ssl, int timeoutSeconds)
    throws IOException {
  URL url = new URL(fullPath);
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  if (ssl) {
    SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    ((HttpsURLConnection) urlConnection).setSSLSocketFactory(socketFactory);
  }
  urlConnection.setReadTimeout(timeoutSeconds * 1000);
  urlConnection.setConnectTimeout(timeoutSeconds * 1000);
  urlConnection.setRequestMethod(httpMethod);
  urlConnection.setDoOutput(!"GET".equals(httpMethod));
  urlConnection.setDoInput(true);
  urlConnection.setUseCaches(false);
  urlConnection.setInstanceFollowRedirects(true);
  Context context = Leanplum.getContext();

  /*
    Must include `Accept-Encoding: gzip` in the header
    Must include the phrase `gzip` in the `User-Agent` header
    https://cloud.google.com/appengine/kb/
  */

  urlConnection.setRequestProperty("User-Agent",
      getApplicationName(context) + "/" + getVersionName() + "/" + RequestOld.appId() + "/" +
          Constants.CLIENT + "/" + Constants.LEANPLUM_VERSION + "/" + getSystemName() + "/" +
          getSystemVersion() + "/" + Constants.LEANPLUM_SUPPORTED_ENCODING + "/" + Constants.LEANPLUM_PACKAGE_IDENTIFIER);
  urlConnection.setRequestProperty("Accept-Encoding", Constants.LEANPLUM_SUPPORTED_ENCODING);
  return urlConnection;
}
 
Example 12
Source File: HttpUtil.java    From jframe with Apache License 2.0 5 votes vote down vote up
private static HttpURLConnection CreatePostHttpConnection(String appKey,
		String appSecret, String uri, String contentType)
		throws MalformedURLException, IOException, ProtocolException {
	String nonce = String.valueOf(Math.random() * 1000000);
	String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
	StringBuilder toSign = new StringBuilder(appSecret).append(nonce)
			.append(timestamp);
	String sign = CodeUtil.hexSHA1(toSign.toString());

	URL url = new URL(uri);
	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	conn.setUseCaches(false);
	conn.setDoInput(true);
	conn.setDoOutput(true);
	conn.setRequestMethod("POST");
	conn.setInstanceFollowRedirects(true);
	conn.setConnectTimeout(30000);
	conn.setReadTimeout(30000);

	conn.setRequestProperty(APPKEY, appKey);
	conn.setRequestProperty(NONCE, nonce);
	conn.setRequestProperty(TIMESTAMP, timestamp);
	conn.setRequestProperty(SIGNATURE, sign);
	conn.setRequestProperty("Content-Type", contentType);

	return conn;
}
 
Example 13
Source File: ImageLoaderOld.java    From 4pdaClient-plus with Apache License 2.0 5 votes vote down vote up
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 = null;
        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);
        FileUtils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
 
Example 14
Source File: RapidShareUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
public static String getData(String url) {

        try {
            u = new URL(url);
            uc = (HttpURLConnection) u.openConnection();
            uc.setDoOutput(true);
            uc.setRequestProperty("Host", "www.rapidshare.com");
            uc.setRequestProperty("Connection", "keep-alive");
            uc.setRequestProperty("Referer", "http://rapidshare.com/");
            uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1");
            uc.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            uc.setRequestProperty("Accept-Encoding", "html");
            uc.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
            uc.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
            uc.setRequestMethod("GET");
            uc.setInstanceFollowRedirects(false);
            br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String temp = "", k = "";
            while ((temp = br.readLine()) != null) {
                //System.out.println(temp);
                k += temp;
            }
            br.close();
            u = null;
            uc = null;
            return k;
        } catch (Exception e) {
            System.out.println("exception : " + e.toString());
            return "";
        }

    }
 
Example 15
Source File: HttpHelper.java    From ZXing-Orient with Apache License 2.0 5 votes vote down vote up
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");
}
 
Example 16
Source File: NetTools.java    From FxDock with Apache License 2.0 5 votes vote down vote up
/** read string content from an http link */
public static String readString(String url) throws Exception
{
	byte[] content;

	HttpURLConnection c = (HttpURLConnection)new URL(url).openConnection();
	//c.setRequestProperty("User-Agent", getUserAgent());
	//c.setConnectTimeout(connectTimeout);
	//c.setReadTimeout(readTimeout);
	c.setRequestProperty("Connection", "close");
	c.setInstanceFollowRedirects(true);
	
	int code = c.getResponseCode();
	if(code != 200)
	{
		throw new Exception("HTTP " + code + " reading " + url);
	}

	InputStream in = getInputStream(c);
	try
	{
		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		CKit.copy(in, ba);
		content = ba.toByteArray();
	}
	finally
	{
		CKit.close(in);
	}
	
	// identify encoding
	String s = new String(content, CKit.CHARSET_UTF8);
	Charset cs = extractCharset(s);
	if(!CKit.CHARSET_UTF8.equals(cs))
	{
		s = new String(content, cs);
	}
	
	return s;
}
 
Example 17
Source File: SimpleClientHttpRequestFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 18
Source File: KerberosWebHDFSConnection2.java    From Transwarp-Sample-Code with MIT License 4 votes vote down vote up
/**
 * 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 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=APPEND", path)), 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;
}
 
Example 19
Source File: RestAppender.java    From karaf-decanter with Apache License 2.0 4 votes vote down vote up
@Override
public void handleEvent(Event event) {
    if (EventFilter.match(event, config)) {
        try {
            HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
            connection.setDoOutput(true);
            connection.setInstanceFollowRedirects(false);
            String user = config.get("user") != null ? (String) config.get("user") : null;
            String password = config.get("password") != null ? (String) config.get("password") : null;
            if (user != null) {
                String authentication = user + ":" + password;
                byte[] encodedAuthentication = Base64.getEncoder().encode(authentication.getBytes(StandardCharsets.UTF_8));
                String authenticationHeader = "Basic " + new String(encodedAuthentication);
                connection.setRequestProperty("Authorization", authenticationHeader);
            }
            String requestMethod = config.get("request.method") != null ? (String) config.get("request.method") : "POST";
            connection.setRequestMethod(requestMethod);
            String contentType = config.get("content.type") != null ? (String) config.get("content.type") : "application/json";
            connection.setRequestProperty("Content-Type",  contentType);
            String charset = config.get("charset") != null ? (String) config.get("charset") : "utf-8";
            connection.setRequestProperty("charset", charset);
            Enumeration<String> keys = config.keys();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                if (key.startsWith("header.")) {
                    connection.setRequestProperty(key.substring("header.".length()), (String) config.get(key));
                }
            }
            String payloadHeader = config.get("payload.header") != null ? (String) config.get("payload.header") : null;
            if (payloadHeader != null) {
                try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                    marshaller.marshal(event, out);
                    connection.setRequestProperty(payloadHeader, out.toString());
                }
            } else {
                try (OutputStream out = connection.getOutputStream()) {
                    marshaller.marshal(event, out);
                }
            }
            InputStream is = connection.getInputStream();
            is.read();
            is.close();
        } catch (Exception e) {
            LOGGER.warn("Error sending event to rest service", e);
        }
    }
}
 
Example 20
Source File: HttpUtil.java    From codewind-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
private static FWAuthToken addAuthIfApplicable(HttpURLConnection connection, AuthTokenWrapper authTokenWrapper) {

		if (authTokenWrapper == null) {
			return null;
		}

		FWAuthToken token = authTokenWrapper.getLatestToken().orElse(null);
		if (token == null) {
			FWLogger.getInstance().logInfo("Requested a secure token from the IDE but got a null");
			return null;
		}

		connection.setInstanceFollowRedirects(false);

		connection.setRequestProperty("Authorization", token.getTokenType() + " " + token.getAccessToken());

		return token;

	}