List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:io.undertow.servlet.test.streams.AbstractServletInputStreamTestCase.java
private void runTestViaJavaImpl(final String message, String url) throws IOException { HttpURLConnection urlcon = null; try {/*from w ww .j a v a 2 s . co m*/ String uri = getBaseUrl() + "/servletContext/" + url; urlcon = (HttpURLConnection) new URL(uri).openConnection(); urlcon.setInstanceFollowRedirects(true); urlcon.setRequestProperty("Connection", "close"); urlcon.setRequestMethod("POST"); urlcon.setDoInput(true); urlcon.setDoOutput(true); OutputStream os = urlcon.getOutputStream(); os.write(message.getBytes()); os.close(); Assert.assertEquals(StatusCodes.OK, urlcon.getResponseCode()); InputStream is = urlcon.getInputStream(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] buf = new byte[256]; int len; while ((len = is.read(buf)) > 0) { bytes.write(buf, 0, len); } is.close(); final String response = new String(bytes.toByteArray(), 0, bytes.size()); if (!message.equals(response)) { System.out.println(String.format("response=%s", Hex.encodeHexString(response.getBytes()))); } Assert.assertEquals(message, response); } finally { if (urlcon != null) { urlcon.disconnect(); } } }
From source file:org.apache.axis2.wsdl.codegen.CodeGenerationEngine.java
/** * @param parser//from w w w. j a v a2 s .c om * @throws CodeGenerationException */ public CodeGenerationEngine(CommandLineOptionParser parser) throws CodeGenerationException { Map allOptions = parser.getAllOptions(); String wsdlUri; try { CommandLineOption option = (CommandLineOption) allOptions .get(CommandLineOptionConstants.WSDL2JavaConstants.WSDL_LOCATION_URI_OPTION); wsdlUri = option.getOptionValue(); // the redirected urls gives problems in code generation some times with jaxbri // eg. https://www.paypal.com/wsdl/PayPalSvc.wsdl // if there is a redirect url better to find it and use. if (wsdlUri.startsWith("http")) { URL url = new URL(wsdlUri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.getResponseCode(); String newLocation = connection.getHeaderField("Location"); if (newLocation != null) { wsdlUri = newLocation; } } configuration = new CodeGenConfiguration(allOptions); if (CommandLineOptionConstants.WSDL2JavaConstants.WSDL_VERSION_2 .equals(configuration.getWSDLVersion())) { WSDL20ToAxisServiceBuilder builder; // jibx currently does not support multiservice if ((configuration.getServiceName() != null) || (configuration.getDatabindingType().equals("jibx"))) { builder = new WSDL20ToAxisServiceBuilder(wsdlUri, configuration.getServiceName(), configuration.getPortName(), configuration.isAllPorts()); builder.setCodegen(true); configuration.addAxisService(builder.populateService()); } else { builder = new WSDL20ToAllAxisServicesBuilder(wsdlUri, configuration.getPortName()); builder.setCodegen(true); builder.setAllPorts(configuration.isAllPorts()); configuration.setAxisServices(((WSDL20ToAllAxisServicesBuilder) builder).populateAllServices()); } } else { //It'll be WSDL 1.1 Definition wsdl4jDef = readInTheWSDLFile(wsdlUri); // we save the original wsdl definition to write it to the resource folder later // this is required only if it has imports Map imports = wsdl4jDef.getImports(); if ((imports != null) && (imports.size() > 0)) { configuration.setWsdlDefinition(readInTheWSDLFile(wsdlUri)); } else { configuration.setWsdlDefinition(wsdl4jDef); } // we generate the code for one service and one port if the // user has specified them. // otherwise generate the code for every service. // TODO: find out a permanant solution for this. QName serviceQname = null; if (configuration.getServiceName() != null) { serviceQname = new QName(wsdl4jDef.getTargetNamespace(), configuration.getServiceName()); } WSDL11ToAxisServiceBuilder builder; // jibx currently does not support multiservice if ((serviceQname != null) || (configuration.getDatabindingType().equals("jibx"))) { builder = new WSDL11ToAxisServiceBuilder(wsdl4jDef, serviceQname, configuration.getPortName(), configuration.isAllPorts()); builder.setCodegen(true); configuration.addAxisService(builder.populateService()); } else { builder = new WSDL11ToAllAxisServicesBuilder(wsdl4jDef, configuration.getPortName()); builder.setCodegen(true); builder.setAllPorts(configuration.isAllPorts()); configuration.setAxisServices(((WSDL11ToAllAxisServicesBuilder) builder).populateAllServices()); } } configuration.setBaseURI(getBaseURI(wsdlUri)); } catch (AxisFault axisFault) { throw new CodeGenerationException(CodegenMessages.getMessage("engine.wsdlParsingException"), axisFault); } catch (WSDLException e) { throw new CodeGenerationException(CodegenMessages.getMessage("engine.wsdlParsingException"), e); } catch (Exception e) { throw new CodeGenerationException(CodegenMessages.getMessage("engine.wsdlParsingException"), e); } loadExtensions(); }
From source file:org.andstatus.app.net.http.HttpConnectionOAuthJavaNet.java
protected void getRequest(HttpReadResult result) throws ConnectionException { String method = "getRequest; "; StringBuilder logBuilder = new StringBuilder(method); try {//from w w w .ja v a 2 s . com OAuthConsumer consumer = getConsumer(); logBuilder.append("URL='" + result.getUrl() + "';"); HttpURLConnection conn; boolean redirected = false; boolean stop = false; do { conn = (HttpURLConnection) result.getUrlObj().openConnection(); conn.setInstanceFollowRedirects(false); if (result.authenticate) { setAuthorization(conn, consumer, redirected); } conn.connect(); result.setStatusCode(conn.getResponseCode()); switch (result.getStatusCode()) { case OK: if (result.fileResult != null) { HttpConnectionUtils.readStreamToFile(conn.getInputStream(), result.fileResult); } else { result.strResponse = HttpConnectionUtils.readStreamToString(conn.getInputStream()); } stop = true; break; case MOVED: redirected = true; result.setUrl(conn.getHeaderField("Location").replace("%3F", "?")); String logMsg3 = (result.redirected ? "Following redirect to " : "Not redirected to ") + "'" + result.getUrl() + "'"; logBuilder.append(logMsg3 + "; "); MyLog.v(this, method + logMsg3); if (MyLog.isLoggable(MyLog.APPTAG, MyLog.VERBOSE)) { StringBuilder message = new StringBuilder(method + "Headers: "); for (Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) { for (String value : entry.getValue()) { message.append(entry.getKey() + ": " + value + ";\n"); } } MyLog.v(this, message.toString()); } conn.disconnect(); break; default: result.strResponse = HttpConnectionUtils.readStreamToString(conn.getErrorStream()); stop = result.fileResult == null || !result.authenticate; if (!stop) { result.authenticate = false; String logMsg4 = "Retrying without authentication connection to '" + result.getUrl() + "'"; logBuilder.append(logMsg4 + "; "); MyLog.v(this, method + logMsg4); } break; } } while (!stop); } catch (ConnectionException e) { throw e; } catch (IOException e) { throw new ConnectionException(logBuilder.toString(), e); } }
From source file:com.android.volley.toolbox.HurlStack.java
/** * Create an {@link HttpURLConnection} for the specified {@code url}. *//* ww w . j a v a2 s . co m*/ protected HttpURLConnection createConnection(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Workaround for the M release HttpURLConnection not observing the // HttpURLConnection.setFollowRedirects() property. // https://code.google.com/p/android/issues/detail?id=194495 connection.setInstanceFollowRedirects(HttpURLConnection.getFollowRedirects()); return connection; }
From source file:org.smartfrog.services.www.bulkio.client.AbstractBulkIOClient.java
/** * Open a connection. The connection is not yet "connected" -you can do some last minute tuning * * @return an HTTP connection./*from ww w . jav a 2 s. c om*/ * @throws IOException */ protected HttpURLConnection openConnection(URL targetURL) throws IOException { HttpURLConnection connection; URLConnection rawConnection = targetURL.openConnection(); if (!(rawConnection instanceof HttpURLConnection)) { throw new IOException("Could not open an HTTP connection to " + targetURL); } connection = (HttpURLConnection) rawConnection; connection.setInstanceFollowRedirects(true); connection.setRequestMethod(operation); if (connectTimeout >= 0) { connection.setConnectTimeout(connectTimeout); } return connection; }
From source file:ja.ohac.wallet.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address... addresses) { backgroundHandler.post(new Runnable() { @Override/*w ww.j av a 2 s . com*/ public void run() { final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL); url.append("unspent-outputs"); url.append("?per_page=MAX"); for (final Address address : addresses) url.append("&address[]=").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 status = json.getInt("status"); if (status != 200) throw new IOException("api status " + status + " when fetching unspent outputs"); final JSONObject jsonData = json.getJSONObject("data"); final JSONObject jsonPagination = jsonData.getJSONObject("pagination"); if (!"false".equals(jsonPagination.getString("next_page"))) throw new IllegalStateException("result set too big"); final JSONArray jsonOutputs = jsonData.getJSONArray("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); if (jsonOutput.getInt("is_spent") != 0) throw new IllegalStateException("UXTO not spent"); final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash")); final int uxtoIndex = jsonOutput.getInt("transaction_index"); final byte[] uxtoScriptBytes = BaseEncoding.base16().lowerCase() .decode(jsonOutput.getString("script_pub_key")); final BigInteger uxtoValue = new BigInteger(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, Coin.valueOf(uxtoValue.longValue()), 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.apache.jmeter.protocol.http.control.TestHTTPMirrorThread.java
public void testQueryRedirect() throws Exception { URL url = new URI("http", null, "localhost", HTTP_SERVER_PORT, "/path", "redirect=/a/b/c/d?q", null) .toURL();//from ww w . ja v a 2s.c o m HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setInstanceFollowRedirects(false); conn.connect(); assertEquals(302, conn.getResponseCode()); assertEquals("Temporary Redirect", conn.getResponseMessage()); assertEquals("/a/b/c/d?q", conn.getHeaderField("Location")); }
From source file:systems.soapbox.ombuds.client.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address... addresses) { backgroundHandler.post(new Runnable() { @Override//from w ww. j a v a 2s .co m public void run() { final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL); url.append("outputs"); url.append("?per_page=MAX"); url.append("&operator=AND"); url.append("&spent_state=UNSPENT"); for (final Address address : addresses) url.append("&address[]=").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 status = json.getInt("status"); if (status != 200) throw new IOException("api status " + status + " when fetching unspent outputs"); final JSONObject jsonData = json.getJSONObject("data"); final JSONObject jsonPagination = jsonData.getJSONObject("pagination"); if (!"false".equals(jsonPagination.getString("next_page"))) throw new IOException("result set too big"); final JSONArray jsonOutputs = jsonData.getJSONArray("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 = Sha256Hash.wrap(jsonOutput.getString("transaction_hash")); final int uxtoIndex = jsonOutput.getInt("transaction_index"); final byte[] uxtoScriptBytes = Constants.HEX .decode(jsonOutput.getString("script_pub_key")); 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:de.schildbach.wallet.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address... addresses) { backgroundHandler.post(new Runnable() { @Override/*from w w w . j av a 2 s . com*/ public void run() { final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL); url.append("unspent-outputs"); url.append("?per_page=MAX"); for (final Address address : addresses) url.append("&address[]=").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 status = json.getInt("status"); if (status != 200) throw new IOException("api status " + status + " when fetching unspent outputs"); final JSONObject jsonData = json.getJSONObject("data"); final JSONObject jsonPagination = jsonData.getJSONObject("pagination"); if (!"false".equals(jsonPagination.getString("next_page"))) throw new IllegalStateException("result set too big"); final JSONArray jsonOutputs = jsonData.getJSONArray("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); if (jsonOutput.getInt("is_spent") != 0) throw new IllegalStateException("UXTO not spent"); final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash")); final int uxtoIndex = jsonOutput.getInt("transaction_index"); final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script_pub_key")); 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:IntergrationTest.OCSPIntegrationTest.java
private byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception { InputStream is = null;// w w w . j av a2s . c om InputStream is_temp = null; try { if (uri == null) return null; URL url = uri.toURL(); if (bActiveCheckUnknownHost) { url.getProtocol(); String host = url.getHost(); int port = url.getPort(); if (port == -1) port = url.getDefaultPort(); InetSocketAddress isa = new InetSocketAddress(host, port); if (isa.isUnresolved()) { //fix JNLP popup error issue throw new UnknownHostException("Host Unknown:" + isa.toString()); } } HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoInput(true); uc.setAllowUserInteraction(false); uc.setInstanceFollowRedirects(true); setTimeout(uc); String contentEncoding = uc.getContentEncoding(); int len = uc.getContentLength(); // is = uc.getInputStream(); if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1) { is_temp = uc.getInputStream(); is = new GZIPInputStream(is_temp); } else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1) { is_temp = uc.getInputStream(); is = new InflaterInputStream(is_temp); } else { is = uc.getInputStream(); } if (len != -1) { int ch, i = 0; byte[] res = new byte[len]; while ((ch = is.read()) != -1) { res[i++] = (byte) (ch & 0xff); } return res; } else { ArrayList<byte[]> buffer = new ArrayList<>(); int buf_len = 1024; byte[] res = new byte[buf_len]; int ch, i = 0; while ((ch = is.read()) != -1) { res[i++] = (byte) (ch & 0xff); if (i == buf_len) { //rotate buffer.add(res); i = 0; res = new byte[buf_len]; } } int total_len = buffer.size() * buf_len + i; byte[] buf = new byte[total_len]; for (int j = 0; j < buffer.size(); j++) { System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len); } if (i > 0) { System.arraycopy(res, 0, buf, buffer.size() * buf_len, i); } return buf; } } catch (Exception e) { e.printStackTrace(); return null; } finally { closeInputStream(is_temp); closeInputStream(is); } }