List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:com.synapticpath.pisecure.modules.LogglyEventLoggerModule.java
private void logEvent(SystemEvent event) { try {/*from ww w. java 2s. c o m*/ byte[] postData = event.toJson().getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; URL url = new URL(String.format(postRequestUrl, token, tag)); 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); } if (conn.getResponseCode() == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder response = new StringBuilder(); String inputLine = null; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.ednovo.goorusearchwidget.WebService.java
public InputStream getHttpStream(String urlString) throws IOException { InputStream in = null;//w w w . jav a 2s .c o m int response = -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); Log.i("Response code :", "" + response); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception e) { throw new IOException("Error connecting"); } // end try-catch return in; }
From source file:org.apache.ambari.servicemonitor.probes.HttpProbe.java
@Override public ProbeStatus ping(boolean livePing) { ProbeStatus status = new ProbeStatus(); HttpURLConnection connection = null; try {/*from ww w . ja va2s . co m*/ if (LOG.isDebugEnabled()) { LOG.debug("Fetching " + url + " with timeout " + timeout); } connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); connection.setConnectTimeout(timeout); int rc = connection.getResponseCode(); if (rc < min || rc > max) { String error = "Probe " + url + " error code: " + rc; LOG.info(error); status.fail(this, new IOException(error)); } else { status.succeed(this); } } catch (IOException e) { String error = "Probe " + url + " failed: " + e; LOG.info(error, e); status.fail(this, new IOException(error, e)); } finally { if (connection != null) { connection.disconnect(); } } return status; }
From source file:com.eucalyptus.tokens.oidc.OidcDiscoveryCache.java
private OidcDiscoveryCachedResource fetchResource(final String url, final long timeNow, final OidcDiscoveryCachedResource cached) throws IOException { final URL location = new URL(url); final OidcResource oidcResource; { // setup url connection and resolve final HttpURLConnection conn = (HttpURLConnection) location.openConnection(); conn.setAllowUserInteraction(false); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); conn.setUseCaches(false);/*from w w w . j av a2s .co m*/ if (cached != null) { if (cached.lastModified.isDefined()) { conn.setRequestProperty(HttpHeaders.IF_MODIFIED_SINCE, cached.lastModified.get()); } if (cached.etag.isDefined()) { conn.setRequestProperty(HttpHeaders.IF_NONE_MATCH, cached.etag.get()); } } oidcResource = resolve(conn); } // build cache entry from resource if (oidcResource.statusCode == 304) { return new OidcDiscoveryCachedResource(timeNow, cached); } else { return new OidcDiscoveryCachedResource(timeNow, Option.of(oidcResource.lastModifiedHeader), Option.of(oidcResource.etagHeader), ImmutableList.copyOf(oidcResource.certs), url, new String(oidcResource.content, StandardCharsets.UTF_8)); } }
From source file:edu.mda.bioinfo.ids.DownloadFiles.java
private void downloadFromHttpToFile(String theURL, String theParameters, String theFile) throws IOException { // both in milliseconds //int connectionTimeout = 1000 * 60 * 3; //int readTimeout = 1000 * 60 * 3; try {/*from ww w . j av a2s . c om*/ URL myURL = new URL(theURL); HttpURLConnection connection = (HttpURLConnection) myURL.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/plain"); //connection.setRequestProperty("charset", "utf-8"); if (null != theParameters) { System.out.println("Content-Length " + Integer.toString(theParameters.getBytes().length)); connection.setRequestProperty("Content-Length", "" + Integer.toString(theParameters.getBytes().length)); } connection.setUseCaches(false); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { if (null != theParameters) { wr.write(theParameters.getBytes()); } wr.flush(); File myFile = new File(theFile); System.out.println("Requesting " + myURL); FileUtils.copyInputStreamToFile(connection.getInputStream(), myFile); System.out.println("Downloaded " + myURL); } catch (IOException rethrownExp) { InputStream errorStr = connection.getErrorStream(); if (null != errorStr) { System.err.println("Error stream returned: " + IOUtils.toString(errorStr)); } else { System.err.println("No error stream returned"); } throw rethrownExp; } } catch (IOException rethrownExp) { System.err.println("exception " + rethrownExp.getMessage() + " thrown while downloading " + theURL + " to " + theFile); throw rethrownExp; } }
From source file:org.cloudfoundry.identity.uaa.integration.TestAccountSetup.java
private OAuth2RestTemplate createRestTemplate(OAuth2ProtectedResourceDetails resource, AccessTokenRequest accessTokenRequest) { OAuth2ClientContext context = new DefaultOAuth2ClientContext(accessTokenRequest); OAuth2RestTemplate client = new OAuth2RestTemplate(resource, context); client.setRequestFactory(new SimpleClientHttpRequestFactory() { @Override/*from ww w .j av a2s. c om*/ protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { super.prepareConnection(connection, httpMethod); connection.setInstanceFollowRedirects(false); } }); client.setErrorHandler(new ResponseErrorHandler() { // Pass errors through in response entity for status code analysis public boolean hasError(ClientHttpResponse response) throws IOException { return false; } public void handleError(ClientHttpResponse response) throws IOException { } }); List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>(); list.add(new StringHttpMessageConverter()); list.add(new MappingJacksonHttpMessageConverter()); client.setMessageConverters(list); return client; }
From source file:com.nbzs.ningbobus.ui.loaders.BusRunInfoReaderLoader.java
private BusLineRunInfoItem downloadOneFeedItem(Integer busLine) { try {//from w ww. j a va 2 s .c om URI newUri = URI.create(mFeedUri.toString() + "/" + Integer.toString(busLine) + "/?format=json"); HttpURLConnection conn = (HttpURLConnection) newUri.toURL().openConnection(); InputStream in; int status; conn.setDoInput(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-Agent", getContext().getString(R.string.user_agent_string)); in = conn.getInputStream(); status = conn.getResponseCode(); if (status < 400) { String result = IOUtils.readStream(in); BusLineRunInfoItem item = new BusLineRunInfoItem(); //result = "{\"RunInfo\" : " + result + "}"; JSONObject jo = new JSONObject(result); //item.setBusLineName(jo.getString("Name")); item.setBusLineCurrentInfo(jo.getString("RunInfo")); //result = URLDecoder.decode(result, "UTF-8"); //item.setBusLineCurrentInfo(result); item.setBusLineName(FeedService.getBusLineFromId(getContext(), busLine)); return item; } conn.disconnect(); } catch (UnknownHostException e) { mActivity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(mActivity, "No network connection.", Toast.LENGTH_SHORT).show(); } }); } catch (IOException e) { Log.d(TAG, "error reading feed"); Log.d(TAG, Log.getStackTraceString(e)); } catch (IllegalStateException e) { Log.d(TAG, "this should not happen"); Log.d(TAG, Log.getStackTraceString(e)); } catch (JSONException e) { Log.d(TAG, "this should not happen"); Log.d(TAG, Log.getStackTraceString(e)); } return null; }
From source file:com.boundary.camel.component.url.UrlClient.java
private void configureConnection(HttpURLConnection connection) throws ProtocolException { connection.setConnectTimeout(configuration.getTimeout()); connection.setRequestMethod(configuration.getRequestMethod()); connection.setInstanceFollowRedirects(configuration.getFollowRedirects()); if (configuration.getUser() != null || configuration.getPassword() != null) { StringBuffer sb = new StringBuffer(); if (configuration.getUser() != null) { sb.append(configuration.getUser()); }//from ww w. ja va2 s . c o m sb.append(":"); if (configuration.getPassword() != null) { sb.append(configuration.getPassword()); } connection.setRequestProperty("Authorization", "Basic " + Base64.encodeBase64String(sb.toString().getBytes())); } }
From source file:de.nava.informa.utils.FeedManagerEntry.java
/** * Updates the channel associated with this feed use conditional get stuff. * http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers * * @throws FeedManagerException/*from w w w . j a va2 s. c o m*/ */ private synchronized void updateChannel() throws FeedManagerException { try { String feedUrl = this.feed.getLocation().toString(); URL aURL = new URL(feedUrl); URLConnection conn = aURL.openConnection(); if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setInstanceFollowRedirects(true); // Hack for User-Agent : problem for // http://www.diveintomark.org/xml/rss.xml HttpHeaderUtils.setUserAgent(httpConn, "Informa Java API"); HttpHeaderUtils.setETagValue(httpConn, this.httpHeaders.getETag()); HttpHeaderUtils.setIfModifiedSince(httpConn, this.httpHeaders.getIfModifiedSince()); httpConn.connect(); if (httpConn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { logger.info("cond. GET for feed at url " + feedUrl + ": no change"); this.feed.setLastUpdated(new Date()); // TODO : add a property in FeedIF interface for lastGet ? this.lastUpdate = System.currentTimeMillis(); return; } logger.info("cond. GET for feed at url " + feedUrl + ": changed"); logger.debug( "feed at url " + feedUrl + " new values : ETag" + HttpHeaderUtils.getETagValue(httpConn) + " if-modified :" + HttpHeaderUtils.getLastModified(httpConn)); this.httpHeaders.setETag(HttpHeaderUtils.getETagValue(httpConn)); this.httpHeaders.setIfModifiedSince(HttpHeaderUtils.getLastModified(httpConn)); } ChannelIF channel; if (conn == null) { channel = FeedParser.parse(getChannelBuilder(), feedUrl); } else { channel = FeedParser.parse(getChannelBuilder(), conn.getInputStream()); } this.feed.setChannel(channel); this.feed.setLastUpdated(new Date()); this.lastUpdate = System.currentTimeMillis(); logger.info("feed updated " + feedUrl); } catch (IOException | ParseException e) { throw new FeedManagerException(e); } }
From source file:edu.mit.mobile.android.net.DownloadLoader.java
@Override public Uri loadInBackground() { boolean alreadyHasDownload = false; if (!outdir.exists() && !outdir.mkdirs()) { mException = new IOException("could not mkdirs: " + outdir.getAbsolutePath()); return null; }//ww w . j a v a 2 s . c o m final String fname = mUrl.substring(mUrl.lastIndexOf('/')); final File outfile = new File(outdir, fname); alreadyHasDownload = outfile.exists() && outfile.length() > MINIMUM_REASONABLE_VIDEO_SIZE; final long lastModified = outfile.exists() ? outfile.lastModified() : 0; try { final NetworkInfo netInfo = mCm.getActiveNetworkInfo(); if (netInfo == null || !netInfo.isConnected()) { // no connection, but there's already a file. Hopefully it works! if (alreadyHasDownload) { return Uri.fromFile(outfile); } else { mException = new IOException(getContext().getString(R.string.err_no_data_connection)); return null; } } HttpURLConnection hc = (HttpURLConnection) new URL(mUrl).openConnection(); hc.setInstanceFollowRedirects(true); if (lastModified != 0) { hc.setIfModifiedSince(lastModified); } int resp = hc.getResponseCode(); if (resp >= 300 && resp < 400) { final String redirectUrl = hc.getURL().toExternalForm(); if (BuildConfig.DEBUG) { Log.d(TAG, "following redirect to " + redirectUrl); } hc = (HttpURLConnection) new URL(redirectUrl).openConnection(); if (lastModified != 0) { hc.setIfModifiedSince(lastModified); } resp = hc.getResponseCode(); } if (resp != HttpStatus.SC_OK && resp != HttpStatus.SC_NOT_MODIFIED) { Log.e(TAG, "got a non-200 response from server"); mException = new NetworkProtocolException("Received " + resp + " response from server"); return null; } if (resp == HttpStatus.SC_NOT_MODIFIED) { if (Constants.DEBUG) { Log.d(TAG, "got NOT MODIFIED"); } // verify the integrity of the file if (alreadyHasDownload) { if (Constants.DEBUG) { Log.d(TAG, fname + " has not been modified since it was downloaded last"); } return Uri.fromFile(outfile); } else { // re-request without the if-modified header. This shouldn't happen. hc = (HttpURLConnection) new URL(mUrl).openConnection(); final int responseCode = hc.getResponseCode(); if (responseCode != HttpStatus.SC_OK) { Log.e(TAG, "got a non-200 response from server"); mException = new NetworkProtocolException( "Received " + responseCode + " response from server"); return null; } } } final int contentLength = hc.getContentLength(); if (contentLength == 0) { Log.e(TAG, "got an empty response from server"); mException = new IOException("Received an empty response from server."); return null; } else if (contentLength < MINIMUM_REASONABLE_VIDEO_SIZE) { // this is probably not a // video Log.e(TAG, "got a very small response from server of length " + hc.getContentLength()); mException = new IOException("Received an unusually-small response from server."); return null; } boolean downloadSucceeded = false; try { final BufferedInputStream bis = new BufferedInputStream(hc.getInputStream()); final FileOutputStream fos = new FileOutputStream(outfile); if (Constants.DEBUG) { Log.d(TAG, "downloading..."); } StreamUtils.inputStreamToOutputStream(bis, fos); fos.close(); // store the server's last modified date in the filesystem outfile.setLastModified(hc.getLastModified()); downloadSucceeded = true; if (Constants.DEBUG) { Log.d(TAG, "done! Saved to " + outfile); } return Uri.fromFile(outfile); } finally { hc.disconnect(); // cleanup if this is the first attempt to download if (!alreadyHasDownload && !downloadSucceeded) { outfile.delete(); } } } catch (final IOException e) { Log.e(TAG, "error downloading file", e); mException = e; return null; } }