List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:com.wadpam.guja.oauth2.social.NetworkTemplate.java
public <J> NetworkResponse<J> exchangeForResponse(String method, String url, Map<String, String> requestHeaders, Object requestBody, Class<J> responseClass, boolean followRedirects) { // so that we can read in case of Exception InputStream in = null;/* w w w .j a v a 2 s . co m*/ try { // expand url? if (null != requestBody && !CONTENT_METHODS.contains(method)) { Map<String, Object> paramMap = requestBody instanceof Map ? (Map) requestBody : MAPPER.convertValue(requestBody, Map.class); url = expandUrl(url, paramMap); } // create the connection URL u = new URL(url); HttpURLConnection con = (HttpURLConnection) u.openConnection(); con.setInstanceFollowRedirects(followRedirects); // override default method if (null != method) { con.setRequestMethod(method); } LOG.info("{} {}", method, url); // Accept if (null != accept) { con.addRequestProperty(ACCEPT, accept); LOG.trace("{}: {}", ACCEPT, accept); } // Authorization if (null != authorization) { con.addRequestProperty(AUTHORIZATION, authorization); LOG.trace("{}: {}", AUTHORIZATION, authorization); } // other request headers: String contentType = null; if (null != requestHeaders) { for (Entry<String, String> entry : requestHeaders.entrySet()) { con.addRequestProperty(entry.getKey(), entry.getValue()); LOG.info("{}: {}", entry.getKey(), entry.getValue()); if (CONTENT_TYPE.equalsIgnoreCase(entry.getKey())) { contentType = entry.getValue(); } } } if (null != requestBody) { if (CONTENT_METHODS.contains(method)) { // content-type not specified in request headers? if (null == contentType) { contentType = MIME_JSON; con.addRequestProperty(CONTENT_TYPE, MIME_JSON); } con.setDoOutput(true); OutputStream out = con.getOutputStream(); if (MIME_JSON.equals(contentType)) { MAPPER.writeValue(out, requestBody); final String json = MAPPER.writeValueAsString(requestBody); LOG.debug("json Content: {}", json); } else { // application/www-form-urlencoded PrintWriter writer = new PrintWriter(out); if (requestBody instanceof String) { writer.print(requestBody); LOG.debug("Content: {}", requestBody); } else { Map<String, Object> params = MAPPER.convertValue(requestBody, Map.class); String content = expandUrl("", params); writer.print(content.substring(1)); LOG.debug("Content: {}", content.substring(1)); } writer.flush(); } out.close(); } } NetworkResponse<J> response = new NetworkResponse<J>(con.getResponseCode(), con.getHeaderFields(), con.getResponseMessage()); LOG.info("HTTP {} {}", response.getCode(), response.getMessage()); // response content to read and parse? if (null != con.getContentType()) { final String responseType = con.getContentType(); LOG.debug("Content-Type: {}", responseType); in = con.getInputStream(); if (con.getContentType().startsWith(MIME_JSON)) { response.setBody(MAPPER.readValue(in, responseClass)); LOG.debug("Response JSON: {}", response.getBody()); } else if (String.class.equals(responseClass)) { String s = readResponseAsString(in, responseType); LOG.info("Read {} bytes from {}", s.length(), con.getContentType()); response.setBody((J) s); } else if (400 <= response.getCode()) { String s = readResponseAsString(in, responseType); LOG.warn(s); } in.close(); } return response; } catch (IOException ioe) { if (null != in) { try { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s; while (null != (s = br.readLine())) { LOG.warn(s); } } catch (IOException ignore) { } } throw new RuntimeException(String.format("NetworkTemplate.exchange: %s", ioe.getMessage()), ioe); } }
From source file:org.talend.camel.designer.ui.editor.CamelTalendEditor.java
protected boolean isAvailableNexus3(ArtifactRepositoryBean nexusServerBean) throws Exception { String authUrl = nexusServerBean.getServer() + (nexusServerBean.getServer().endsWith("/") ? "" : "/") + "service/rapture/session?_dc=" + System.currentTimeMillis(); URL url = new URL(authUrl); String urlParameters = "username=" + java.util.Base64.getEncoder().encodeToString(nexusServerBean.getUserName().getBytes()) + "&password=" + java.util.Base64.getEncoder().encodeToString(nexusServerBean.getPassword().getBytes()); byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);/* www . j a va 2 s . c om*/ 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); } int state = conn.getResponseCode(); if (state == 204) { return true; } else if (state == 401) { MessageDialog.openError(getParent().getEditorSite().getShell(), "Checking Nexus Connection Error", "Can not connect to " + nexusServerBean.getServer() + "\n" + conn.getResponseMessage() + " ResponseCode : " + state + " Please upload the related jar files manually"); } return false; }
From source file:com.juce.JuceAppActivity.java
public static final HTTPStream createHTTPStream (String address, boolean isPost, byte[] postData, String headers, int timeOutMs, int[] statusCode, StringBuffer responseHeaders, int numRedirectsToFollow, String httpRequestCmd) { // timeout parameter of zero for HttpUrlConnection is a blocking connect (negative value for juce::URL) if (timeOutMs < 0) timeOutMs = 0;/*from w ww . ja v a 2 s.co m*/ else if (timeOutMs == 0) timeOutMs = 30000; // headers - if not empty, this string is appended onto the headers that are used for the request. It must therefore be a valid set of HTML header directives, separated by newlines. // So convert headers string to an array, with an element for each line String headerLines[] = headers.split("\\n"); for (;;) { try { HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection()); if (connection != null) { try { connection.setInstanceFollowRedirects (false); connection.setConnectTimeout (timeOutMs); connection.setReadTimeout (timeOutMs); // Set request headers for (int i = 0; i < headerLines.length; ++i) { int pos = headerLines[i].indexOf (":"); if (pos > 0 && pos < headerLines[i].length()) { String field = headerLines[i].substring (0, pos); String value = headerLines[i].substring (pos + 1); if (value.length() > 0) connection.setRequestProperty (field, value); } } connection.setRequestMethod (httpRequestCmd); if (isPost) { connection.setDoOutput (true); if (postData != null) { OutputStream out = connection.getOutputStream(); out.write(postData); out.flush(); } } HTTPStream httpStream = new HTTPStream (connection, statusCode, responseHeaders); // Process redirect & continue as necessary int status = statusCode[0]; if (--numRedirectsToFollow >= 0 && (status == 301 || status == 302 || status == 303 || status == 307)) { // Assumes only one occurrence of "Location" int pos1 = responseHeaders.indexOf ("Location:") + 10; int pos2 = responseHeaders.indexOf ("\n", pos1); if (pos2 > pos1) { String newLocation = responseHeaders.substring(pos1, pos2); // Handle newLocation whether it's absolute or relative URL baseUrl = new URL (address); URL newUrl = new URL (baseUrl, newLocation); String transformedNewLocation = newUrl.toString(); if (transformedNewLocation != address) { address = transformedNewLocation; // Clear responseHeaders before next iteration responseHeaders.delete (0, responseHeaders.length()); continue; } } } return httpStream; } catch (Throwable e) { connection.disconnect(); } } } catch (Throwable e) {} return null; } }
From source file:org.bibsonomy.scraper.url.kde.blackwell.BlackwellSynergyScraper.java
/** FIXME: refactor * Extract the content of a scitation.aip.org page. * (changed code from ScrapingContext.getContentAsString) * @param urlConn Connection to api page (from url.openConnection()) * @param cookie Cookie for auth.// w w w .j a v a2 s .c om * @return Content of aip page. * @throws IOException */ private String getPageContent(HttpURLConnection urlConn, String cookie) throws IOException { urlConn.setAllowUserInteraction(true); urlConn.setDoInput(true); urlConn.setDoOutput(false); urlConn.setUseCaches(false); urlConn.setFollowRedirects(true); urlConn.setInstanceFollowRedirects(false); urlConn.setRequestProperty("Cookie", cookie); urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)"); urlConn.connect(); // build content StringWriter out = new StringWriter(); InputStream in = new BufferedInputStream(urlConn.getInputStream()); int b; while ((b = in.read()) >= 0) { out.write(b); } urlConn.disconnect(); in.close(); out.flush(); out.close(); return out.toString(); }
From source file:com.amastigote.xdu.query.module.EduSystem.java
private void preLogin() throws IOException { URL url = new URL(SYS_HOST); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setInstanceFollowRedirects(false); httpURLConnection.connect();//ww w .j a va 2 s . c om List<String> cookies_to_set_a = httpURLConnection.getHeaderFields().get("Set-Cookie"); for (String e : cookies_to_set_a) if (e.contains("JSESSIONID=")) SYS_JSESSIONID = e.substring(e.indexOf("JSESSIONID=") + 11, e.indexOf(";")); httpURLConnection.disconnect(); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setInstanceFollowRedirects(true); httpURLConnection.connect(); List<String> cookies_to_set = httpURLConnection.getHeaderFields().get("Set-Cookie"); for (String e : cookies_to_set) { if (e.contains("route=")) ROUTE = e.substring(6); else if (e.contains("JSESSIONID=")) LOGIN_JSESSIONID = e.substring(11, e.indexOf(";")); else if (e.contains("BIGipServeridsnew.xidian.edu.cn=")) BIGIP_SERVER_IDS_NEW = e.substring(32, e.indexOf(";")); } BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(httpURLConnection.getInputStream())); String html = ""; String temp; while ((temp = bufferedReader.readLine()) != null) { html += temp; } Document document = Jsoup.parse(html); Elements elements = document.select("input[type=hidden]"); for (Element element : elements) { switch (element.attr("name")) { case "lt": LOGIN_PARAM_lt = element.attr("value"); break; case "execution": LOGIN_PARAM_execution = element.attr("value"); break; case "_eventId": LOGIN_PARAM__eventId = element.attr("value"); break; case "rmShown": LOGIN_PARAM_rmShown = element.attr("value"); break; } } }
From source file:mobac.mapsources.loader.MapPackManager.java
public String downloadMD5SumList() throws IOException, UpdateFailedException { String md5eTag = Settings.getInstance().mapSourcesUpdate.etag; log.debug("Last md5 eTag: " + md5eTag); String updateUrl = System.getProperty("mobac.updateurl"); if (updateUrl == null) throw new RuntimeException("Update url not present"); byte[] data = null; // Proxy p = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved("localhost", 8888)); HttpURLConnection conn = (HttpURLConnection) new URL(updateUrl).openConnection(); conn.setInstanceFollowRedirects(false); if (md5eTag != null) conn.addRequestProperty("If-None-Match", md5eTag); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { log.debug("No newer md5 file available"); return null; }//www . j a v a2 s.c o m if (responseCode != HttpURLConnection.HTTP_OK) throw new UpdateFailedException( "Invalid HTTP response: " + responseCode + " for update url " + conn.getURL()); // Case HTTP_OK InputStream in = conn.getInputStream(); data = Utilities.getInputBytes(in); in.close(); Settings.getInstance().mapSourcesUpdate.etag = conn.getHeaderField("ETag"); log.debug("New md5 file retrieved"); String md5sumList = new String(data); return md5sumList; }
From source file:osmcd.mapsources.loader.MapPackManager.java
public String downloadMD5SumList() throws IOException, UpdateFailedException { String md5eTag = Settings.getInstance().mapSourcesUpdate.etag; log.debug("Last md5 eTag: " + md5eTag); String updateUrl = System.getProperty("osmcd.updateurl"); if (updateUrl == null) throw new RuntimeException("Update url not present"); byte[] data = null; // Proxy p = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved("localhost", 8888)); HttpURLConnection conn = (HttpURLConnection) new URL(updateUrl).openConnection(); conn.setInstanceFollowRedirects(false); if (md5eTag != null) conn.addRequestProperty("If-None-Match", md5eTag); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { log.debug("No newer md5 file available"); return null; }//ww w . j a va 2 s. c o m if (responseCode != HttpURLConnection.HTTP_OK) throw new UpdateFailedException( "Invalid HTTP response: " + responseCode + " for update url " + conn.getURL()); // Case HTTP_OK InputStream in = conn.getInputStream(); data = Utilities.getInputBytes(in); in.close(); Settings.getInstance().mapSourcesUpdate.etag = conn.getHeaderField("ETag"); log.debug("New md5 file retrieved"); String md5sumList = new String(data); return md5sumList; }
From source file:de.langerhans.wallet.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address address) { backgroundHandler.post(new Runnable() { @Override/*from ww w. j a v a 2s .c o m*/ public void run() { // Use either dogechain or chain.so List<String> urls = new ArrayList<String>(2); urls.add(Constants.DOGECHAIN_API_URL); urls.add(Constants.CHAINSO_API_URL); Collections.shuffle(urls, new Random(System.nanoTime())); final StringBuilder url = new StringBuilder(urls.get(0)); url.append(address.toString()); log.debug("trying to request wallet balance from {}", url); HttpURLConnection connection = null; Reader reader = null; try { connection = (HttpURLConnection) new URL(url.toString()).openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(false); connection.setRequestMethod("GET"); if (userAgent != null) connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Charsets.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final JSONObject json = new JSONObject(content.toString()); final int success = json.getInt("success"); if (success != 1) throw new IOException("api status " + success + " when fetching unspent outputs"); final JSONArray jsonOutputs = json.getJSONArray("unspent_outputs"); final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>( jsonOutputs.length()); for (int i = 0; i < jsonOutputs.length(); i++) { final JSONObject jsonOutput = jsonOutputs.getJSONObject(i); final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("tx_hash")); final int uxtoIndex = jsonOutput.getInt("tx_output_n"); final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script")); final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value"))); Transaction tx = transactions.get(uxtoHash); if (tx == null) { tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash); tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING); transactions.put(uxtoHash, tx); } if (tx.getOutputs().size() > uxtoIndex) throw new IllegalStateException("cannot reach index " + uxtoIndex + ", tx already has " + tx.getOutputs().size() + " outputs"); // fill with dummies while (tx.getOutputs().size() < uxtoIndex) tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.NEGATIVE_SATOSHI, new byte[] {})); // add the real output final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, uxtoValue, uxtoScriptBytes); tx.addOutput(output); } log.info("fetched unspent outputs from {}", url); onResult(transactions.values()); } else { final String responseMessage = connection.getResponseMessage(); log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final JSONException x) { log.info("problem parsing json from " + url, x); onFail(R.string.error_parse, x.getMessage()); } catch (final IOException x) { log.info("problem querying unspent outputs from " + url, x); onFail(R.string.error_io, x.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } } }); }
From source file:org.springframework.security.oauth2.client.test.OAuth2ContextSetup.java
private OAuth2RestTemplate createRestTemplate(OAuth2ProtectedResourceDetails resource, AccessTokenRequest request) {//w w w. j ava2s. c o m OAuth2ClientContext context = new DefaultOAuth2ClientContext(request); OAuth2RestTemplate client = new OAuth2RestTemplate(resource, context); client.setRequestFactory(new SimpleClientHttpRequestFactory() { @Override 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 { } }); if (accessTokenProvider != null) { client.setAccessTokenProvider(accessTokenProvider); } return client; }
From source file:org.cloudfoundry.identity.api.web.ServerRunning.java
public RestOperations createRestTemplate() { RestTemplate client = new RestTemplate(); client.setRequestFactory(new SimpleClientHttpRequestFactory() { @Override/* w w w. j av a2 s.c o m*/ 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 @Override public boolean hasError(ClientHttpResponse response) throws IOException { return false; } @Override public void handleError(ClientHttpResponse response) throws IOException { } }); return client; }