List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:org.apache.openaz.xacml.pdp.test.TestBase.java
/** * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. * * @param file//from w w w .j ava2 s .c om * @return */ protected Response callRESTfulPDP(InputStream is) { Response response = null; HttpURLConnection connection = null; try { // // Open up the connection // connection = (HttpURLConnection) this.restURL.openConnection(); connection.setRequestProperty("Content-Type", "application/json"); // // Setup our method and headers // connection.setRequestMethod("POST"); connection.setUseCaches(false); // // Adding this in. It seems the HttpUrlConnection class does NOT // properly forward our headers for POST re-direction. It does so // for a GET re-direction. // // So we need to handle this ourselves. // connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setDoInput(true); // // Send the request // try (OutputStream os = connection.getOutputStream()) { IOUtils.copy(is, os); } // // Do the connect // connection.connect(); if (connection.getResponseCode() == 200) { // // Read the response // ContentType contentType = null; try { contentType = ContentType.parse(connection.getContentType()); if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { response = JSONResponse.load(connection.getInputStream()); } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { response = DOMResponse.load(connection.getInputStream()); } else { logger.error("unknown content-type: " + contentType); } } catch (Exception e) { String message = "Parsing Content-Type: " + connection.getContentType() + ", error=" + e.getMessage(); logger.error(message, e); } } else { logger.error(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (Exception e) { logger.error(e); } return response; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Retrieves the token from the token pool service. * * @param owner_id which is operator in Token Pool service * @return access token/* w w w . j a v a 2 s .co m*/ * @throws Exception */ private String getPoolAccessToken(String owner_id, String resourceURL) throws Exception { StringBuffer result = new StringBuffer(); HttpURLConnection poolConnection = null; URL requestUrl; try { requestUrl = new URL(resourceURL + URLEncoder.encode(owner_id, "UTF-8")); poolConnection = (HttpURLConnection) requestUrl.openConnection(); poolConnection.setDoOutput(true); poolConnection.setInstanceFollowRedirects(false); poolConnection.setRequestMethod("GET"); poolConnection.setRequestProperty("Accept", "application/json"); poolConnection.setUseCaches(false); InputStream input = null; if (poolConnection.getResponseCode() == 200) { input = poolConnection.getInputStream(); } else { input = poolConnection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(input)); String output; while ((output = br.readLine()) != null) { result.append(output); } br.close(); } catch (Exception e) { log.error("[TokenPoolRequestService ], getPoolAccessToken, " + e.getMessage()); return null; } finally { if (poolConnection != null) { poolConnection.disconnect(); } } return result.toString(); }
From source file:de.sjka.logstash.osgi.internal.LogstashSender.java
private void process(LogEntry logEntry) { if (logEntry.getLevel() <= getLogLevelConfig()) { if (!"true".equals(getConfig(LogstashConfig.ENABLED))) { return; }/*from www . j av a2 s .c om*/ ; for (ILogstashFilter logstashFilter : logstashFilters) { if (!logstashFilter.apply(logEntry)) { return; } } String request = getConfig(LogstashConfig.URL); if (!request.endsWith("/")) { request += "/"; } HttpURLConnection conn = null; try { JSONObject values = serializeLogEntry(logEntry); String payload = values.toJSONString(); byte[] postData = payload.getBytes(StandardCharsets.UTF_8); String username = getConfig(LogstashConfig.USERNAME); String password = getConfig(LogstashConfig.PASSWORD); String authString = username + ":" + password; byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); URL url = new URL(request); conn = (HttpURLConnection) url.openConnection(); if (request.startsWith("https") && "true".equals(getConfig(LogstashConfig.SSL_NO_CHECK))) { if (sslSocketFactory != null) { ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory); ((HttpsURLConnection) conn).setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } } conn.setDoOutput(true); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("charset", "utf-8"); conn.setReadTimeout(30 * SECONDS); conn.setConnectTimeout(30 * SECONDS); if (username != null && !"".equals(username)) { conn.setRequestProperty("Authorization", "Basic " + authStringEnc); } conn.setUseCaches(false); try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) { wr.write(postData); wr.flush(); wr.close(); } if (conn.getResponseCode() != 200) { throw new IOException( "Got response " + conn.getResponseCode() + " - " + conn.getResponseMessage()); } } catch (IOException e) { throw new RuntimeException(e); } finally { if (conn != null) { conn.disconnect(); } } } }
From source file:org.apache.openaz.xacml.rest.XACMLPdpRegisterThread.java
/** * This is our thread that runs on startup to tell the PAP server we are up-and-running. *///from w w w . ja va 2 s .c o m @Override public void run() { synchronized (this) { this.isRunning = true; } boolean registered = false; boolean interrupted = false; int seconds; try { seconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_SLEEP)); } catch (NumberFormatException e) { logger.error("REGISTER_SLEEP: ", e); seconds = 5; } if (seconds < 5) { seconds = 5; } int retries; try { retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_RETRIES)); } catch (NumberFormatException e) { logger.error("REGISTER_SLEEP: ", e); retries = -1; } while (!registered && !interrupted && this.isRunning()) { HttpURLConnection connection = null; try { // // Get the PAP Servlet URL // URL url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)); logger.info("Registering with " + url.toString()); boolean finished = false; while (!finished) { // // Open up the connection // connection = (HttpURLConnection) url.openConnection(); // // Setup our method and headers // connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "text/x-java-properties"); connection.setRequestProperty("Content-Type", "text/x-java-properties"); connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID)); connection.setUseCaches(false); // // Adding this in. It seems the HttpUrlConnection class does NOT // properly forward our headers for POST re-direction. It does so // for a GET re-direction. // // So we need to handle this ourselves. // connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setDoInput(true); try { // // Send our current policy configuration // String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES) + "\n"; try (InputStream listsInputStream = new ByteArrayInputStream(lists.getBytes()); InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig()); OutputStream os = connection.getOutputStream()) { IOUtils.copy(listsInputStream, os); // // Send our current PIP configuration // IOUtils.copy(pipInputStream, os); } } catch (Exception e) { logger.error("Failed to send property file", e); } // // Do the connect // connection.connect(); if (connection.getResponseCode() == 204) { logger.info("Success. We are configured correctly."); finished = true; registered = true; } else if (connection.getResponseCode() == 200) { logger.info("Success. We have a new configuration."); Properties properties = new Properties(); properties.load(connection.getInputStream()); logger.info("New properties: " + properties.toString()); // // Queue it // // The incoming properties does NOT include urls PutRequest req = new PutRequest(XACMLProperties.getPolicyProperties(properties, false), XACMLProperties.getPipProperties(properties)); XACMLPdpServlet.queue.offer(req); // // We are now registered // finished = true; registered = true; } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { // // Re-direction // String newLocation = connection.getHeaderField("Location"); if (newLocation == null || newLocation.isEmpty()) { logger.warn("Did not receive a valid re-direction location"); finished = true; } else { logger.info("New Location: " + newLocation); url = new URL(newLocation); } } else { logger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); finished = true; } } } catch (Exception e) { logger.error(e); } finally { // cleanup the connection if (connection != null) { try { // For some reason trying to get the inputStream from the connection // throws an exception rather than returning null when the InputStream does not exist. InputStream is = null; try { is = connection.getInputStream(); } catch (Exception e1) { //NOPMD // ignore this } if (is != null) { is.close(); } } catch (IOException ex) { logger.error("Failed to close connection: " + ex, ex); } connection.disconnect(); } } // // Wait a little while to try again // try { if (!registered) { if (retries > 0) { retries--; } else if (retries == 0) { break; } Thread.sleep(seconds * 1000); } } catch (InterruptedException e) { interrupted = true; this.terminate(); } } synchronized (this) { this.isRunning = false; } logger.info("Thread exiting...(registered=" + registered + ", interrupted=" + interrupted + ", isRunning=" + this.isRunning() + ", retries=" + retries + ")"); }
From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java
private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status) throws IOException { AQUtility.debug("multipart", url); HttpURLConnection conn = null; DataOutputStream dos = null;/*from w ww . j a v a2s .c o m*/ URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(NET_TIMEOUT * 4); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary); if (headers != null) { for (String name : headers.keySet()) { conn.setRequestProperty(name, headers.get(name)); } } String cookie = makeCookie(); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } if (ah != null) { ah.applyToken(this, conn); } dos = new DataOutputStream(conn.getOutputStream()); Object o = null; if (progress != null) { o = progress.get(); } Progress p = null; if (o != null) { p = new Progress(o); } for (Map.Entry<String, Object> entry : params.entrySet()) { writeObject(dos, entry.getKey(), entry.getValue(), p); } dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); conn.connect(); int code = conn.getResponseCode(); String message = conn.getResponseMessage(); byte[] data = null; String encoding = conn.getContentEncoding(); String error = null; if ((code < 200) || (code >= 300)) { error = new String(toData(encoding, conn.getErrorStream()), "UTF-8"); AQUtility.debug("error", error); } else { data = toData(encoding, conn.getInputStream()); } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null); }
From source file:dentex.youtube.downloader.ShareActivity.java
private String downloadUrl(String myurl) throws IOException { InputStream is = null;/* w ww. ja v a 2s . c om*/ // Only display the first "len" characters of the retrieved web page content. int len = 2000000; Utils.logger("d", "The link is: " + myurl, DEBUG_TAG); if (!asyncDownload.isCancelled()) { try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "<em>" + USER_AGENT_FIREFOX + "</em>"); conn.setReadTimeout(20000 /* milliseconds */); conn.setConnectTimeout(30000 /* milliseconds */); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("GET"); conn.setDoInput(true); //Starts the query conn.connect(); int response = conn.getResponseCode(); Utils.logger("d", "The response is: " + response, DEBUG_TAG); is = conn.getInputStream(); //Convert the InputStream into a string if (!asyncDownload.isCancelled()) { return readIt(is, len); } else { Utils.logger("d", "asyncDownload cancelled @ 'return readIt'", DEBUG_TAG); return null; } //Makes sure that the InputStream is closed after the app is finished using it. } finally { if (is != null) { is.close(); } } } else { Utils.logger("d", "asyncDownload cancelled @ 'downloadUrl' begin", DEBUG_TAG); return null; } }
From source file:com.becapps.easydownloader.ShareActivity.java
private String downloadUrl(String myurl) throws IOException, RuntimeException { InputStream is = null;//from w ww . ja v a 2s. co m // Only display the first "len" characters of the retrieved web page content. int len = 2000000; Utils.logger("d", "The link is: " + myurl, DEBUG_TAG); if (!asyncDownload.isCancelled()) { try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "<em>" + USER_AGENT_FIREFOX + "</em>"); conn.setReadTimeout(20000 /* milliseconds */); conn.setConnectTimeout(30000 /* milliseconds */); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("GET"); conn.setDoInput(true); //Starts the query conn.connect(); int response = conn.getResponseCode(); Utils.logger("d", "The response is: " + response, DEBUG_TAG); is = conn.getInputStream(); //Convert the InputStream into a string if (!asyncDownload.isCancelled()) { return readIt(is, len); } else { Utils.logger("d", "asyncDownload cancelled @ 'return readIt'", DEBUG_TAG); return null; } //Makes sure that the InputStream is closed after the app is finished using it. } finally { if (is != null) { is.close(); } } } else { Utils.logger("d", "asyncDownload cancelled @ 'downloadUrl' begin", DEBUG_TAG); return null; } }
From source file:org.ramadda.util.Utils.java
/** * _more_/*from w w w .j a va2 s . co m*/ * * @param action _more_ * @param url _more_ * @param body _more_ * @param args _more_ * * @return _more_ * * @throws Exception _more_ */ public static String doHttpRequest(String action, URL url, String body, String... args) throws Exception { // URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod(action); connection.setRequestProperty("charset", "utf-8"); for (int i = 0; i < args.length; i += 2) { // System.err.println(args[i]+":" + args[i+1]); connection.setRequestProperty(args[i], args[i + 1]); } if (body != null) { connection.setRequestProperty("Content-Length", Integer.toString(body.length())); connection.getOutputStream().write(body.getBytes()); } try { return readString(new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))); } catch (Exception exc) { System.err.println("Utils: error doing http request:" + action + "\nURL:" + url + "\nreturn code:" + connection.getResponseCode() + "\nBody:" + body); System.err.println(readError(connection)); System.err.println(connection.getHeaderFields()); throw exc; // System.err.println(connection.getContent()); } }
From source file:org.ohmage.service.UserServices.java
/** * Verifies that the given captcha information is valid. * /*from w w w.j a va 2 s .c om*/ * @param remoteAddr The address of the remote host. * * @param challenge The challenge value. * * @param response The response value. * * @throws ServiceException Thrown if the private key is missing or if the * response is invalid. */ public void verifyCaptchaV2(final String remoteAddr, final String response) throws ServiceException { String secretKey; URL url = null; String postData = null; try { secretKey = PreferenceCache.instance().lookup(PreferenceCache.KEY_RECAPTCHA_KEY_PRIVATE); } catch (CacheMissException e) { throw new ServiceException("The ReCaptcha key is missing from the preferences: " + PreferenceCache.KEY_RECAPTCHA_KEY_PRIVATE, e); } if ((response == null) || (response.length() == 0)) throw new ServiceException(ErrorCode.SERVER_INVALID_CAPTCHA, "The reCaptcha response was invalid."); try { // prepare post data StringBuilder param = new StringBuilder(); param.append("secret=" + URLEncoder.encode(secretKey.toString(), "UTF-8")); param.append("&response=" + URLEncoder.encode(response.toString(), "UTF-8")); if ((remoteAddr != null) && (remoteAddr.length() > 0)) param.append("&remoteip=" + URLEncoder.encode(response.toString(), "UTF-8")); postData = param.toString(); url = new URL("https://www.google.com/recaptcha/api/siteverify"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", Integer.toString(postData.length())); connection.setUseCaches(false); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(postData); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder strBuilder = new StringBuilder(); String tmp_str; while ((tmp_str = in.readLine()) != null) strBuilder.append(tmp_str); in.close(); String result = strBuilder.toString(); if (result.length() == 0) { throw new ServiceException(ErrorCode.SERVER_INVALID_CAPTCHA, "The reCaptcha response was invalid."); } // System.out.println(result); try { JSONObject jsonResult = new JSONObject(result); if (!jsonResult.getBoolean("success")) { throw new JSONException("Recaptcha failed to verify"); } } catch (JSONException e) { throw new ServiceException(ErrorCode.SERVER_INVALID_CAPTCHA, "The reCaptcha response was invalid."); } } catch (MalformedURLException e) { throw new ServiceException("MalformedURL: " + url.toString(), e); } catch (UnsupportedEncodingException e) { throw new ServiceException("UnsupportedEncoding: Can't encode post-data: " + postData, e); } catch (IOException e) { throw new ServiceException("IOEncoding: URL=" + url.toString() + ", post-data: " + postData, e); } }