List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:net.technicpack.launchercore.mirror.MirrorStore.java
public String getETag(String address) { String md5 = ""; try {/*from w w w . j a v a 2 s . co m*/ URL url = getFullUrl(address); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(false); System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); HttpURLConnection.setFollowRedirects(true); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); String eTag = conn.getHeaderField("ETag"); if (eTag != null) { eTag = eTag.replaceAll("^\"|\"$", ""); if (eTag.length() == 32) { md5 = eTag; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return md5; }
From source file:org.dcm4che3.tool.stowrs.StowRS.java
private StowRSResponse sendMetaDataAndBulkData(Attributes metadata, ExtractedBulkData extractedBulkData) throws IOException { Attributes responseAttrs = new Attributes(); URL newUrl;/*from w w w . j a va2 s. com*/ try { newUrl = new URL(URL); } catch (MalformedURLException e2) { throw new RuntimeException(e2); } HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection(); connection.setChunkedStreamingMode(2048); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); String metaDataType = mediaType == StowMetaDataType.XML ? "application/dicom+xml" : "application/json"; connection.setRequestProperty("Content-Type", "multipart/related; type=" + metaDataType + "; boundary=" + MULTIPART_BOUNDARY); String bulkDataTransferSyntax = "transfer-syntax=" + transferSyntax; MediaType pixelDataMediaType = getBulkDataMediaType(metadata); connection.setRequestProperty("Accept", "application/dicom+xml"); connection.setRequestProperty("charset", "utf-8"); connection.setUseCaches(false); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); // write metadata wr.writeBytes("\r\n--" + MULTIPART_BOUNDARY + "\r\n"); if (mediaType == StowMetaDataType.XML) wr.writeBytes("Content-Type: application/dicom+xml; " + bulkDataTransferSyntax + " \r\n"); else wr.writeBytes("Content-Type: application/json; " + bulkDataTransferSyntax + " \r\n"); wr.writeBytes("\r\n"); coerceAttributes(metadata, keys); try { if (mediaType == StowMetaDataType.XML) SAXTransformer.getSAXWriter(new StreamResult(wr)).write(metadata); else { JsonGenerator gen = Json.createGenerator(wr); JSONWriter writer = new JSONWriter(gen); writer.write(metadata); gen.flush(); } } catch (TransformerConfigurationException e) { throw new IOException(e); } catch (SAXException e) { throw new IOException(e); } // write bulkdata for (BulkData chunk : extractedBulkData.otherBulkDataChunks) { writeBulkDataPart(MediaType.APPLICATION_OCTET_STREAM_TYPE, wr, chunk.getURIOrUUID(), Collections.singletonList(chunk)); } if (!extractedBulkData.pixelDataBulkData.isEmpty()) { // pixeldata as a single bulk data part if (extractedBulkData.pixelDataBulkData.size() > 1) { LOG.info("Combining bulk data of multiple pixel data fragments"); } writeBulkDataPart(pixelDataMediaType, wr, extractedBulkData.pixelDataBulkDataURI, extractedBulkData.pixelDataBulkData); } // end of multipart message wr.writeBytes("\r\n--" + MULTIPART_BOUNDARY + "--\r\n"); wr.close(); String response = connection.getResponseMessage(); int rspCode = connection.getResponseCode(); LOG.info("response: " + response); try { responseAttrs = SAXReader.parse(connection.getInputStream()); } catch (Exception e) { LOG.error("Error creating response attributes", e); } connection.disconnect(); return new StowRSResponse(rspCode, response, responseAttrs); }
From source file:com.portfolio.data.attachment.XSLService.java
HttpURLConnection CreateConnection(String url, HttpServletRequest request) throws MalformedURLException, IOException { /// Create connection URL urlConn = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlConn.openConnection(); connection.setDoOutput(true);/* www. java2s. co m*/ connection.setUseCaches(false); /// We don't want to cache data connection.setInstanceFollowRedirects(false); /// Let client follow any redirection String method = request.getMethod(); connection.setRequestMethod(method); String context = request.getContextPath(); connection.setRequestProperty("app", context); /// Transfer headers String key = ""; String value = ""; Enumeration<String> header = request.getHeaderNames(); while (header.hasMoreElements()) { key = header.nextElement(); value = request.getHeader(key); connection.setRequestProperty(key, value); } return connection; }
From source file:org.jclouds.http.internal.JavaUrlHttpCommandExecutorService.java
@Override protected HttpURLConnection convert(HttpRequest request) throws IOException { URL url = request.getEndpoint().toURL(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (relaxHostname && connection instanceof HttpsURLConnection) { HttpsURLConnection sslCon = (HttpsURLConnection) connection; sslCon.setHostnameVerifier(new LogToMapHostnameVerifier()); }//w w w . ja v a 2s . c o m connection.setDoOutput(true); connection.setAllowUserInteraction(false); // do not follow redirects since https redirects don't work properly // ex. Caused by: java.io.IOException: HTTPS hostname wrong: should be // <adriancole.s3int0.s3-external-3.amazonaws.com> connection.setInstanceFollowRedirects(false); connection.setRequestMethod(request.getMethod().toString()); for (String header : request.getHeaders().keySet()) { for (String value : request.getHeaders().get(header)) { connection.setRequestProperty(header, value); if ("Transfer-Encoding".equals(header) && "chunked".equals(value)) { connection.setChunkedStreamingMode(8192); } } } connection.setRequestProperty(HttpHeaders.HOST, request.getEndpoint().getHost()); if (request.getEntity() != null) { OutputStream out = connection.getOutputStream(); try { if (request.getEntity() instanceof String) { OutputStreamWriter writer = new OutputStreamWriter(out); writer.write((String) request.getEntity()); writer.close(); } else if (request.getEntity() instanceof InputStream) { IOUtils.copy((InputStream) request.getEntity(), out); } else if (request.getEntity() instanceof File) { IOUtils.copy(new FileInputStream((File) request.getEntity()), out); } else if (request.getEntity() instanceof byte[]) { IOUtils.write((byte[]) request.getEntity(), out); } else { throw new UnsupportedOperationException( "Content not supported " + request.getEntity().getClass()); } } finally { IOUtils.closeQuietly(out); } } else { connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, "0"); } return connection; }
From source file:org.mozilla.mozstumbler.service.core.http.HttpUtil.java
private IResponse getHttpResponse(String urlString, Map<String, String> headers, String HTTP_METHOD) { URL url = null;/*from w w w . j ava 2s. c o m*/ HttpURLConnection httpURLConnection = null; try { url = new URL(urlString); } catch (MalformedURLException e) { Log.e(LOG_TAG, "Bad URL", e); return null; } if (headers == null) { headers = new HashMap<String, String>(); } try { httpURLConnection = (HttpURLConnection) url.openConnection(); if (HTTP_METHOD.toUpperCase().equals("HEAD")) { httpURLConnection.setInstanceFollowRedirects(false); } httpURLConnection.setConnectTimeout(5000); // set timeout to 5 seconds httpURLConnection.setRequestMethod(HTTP_METHOD); httpURLConnection.setRequestProperty(USER_AGENT_HEADER, userAgent); } catch (IOException e) { Log.e(LOG_TAG, "Couldn't open a connection: ", e); return null; } // Workaround for a bug in Android mHttpURLConnection. When the library // reuses a stale connection, the connection may fail with an EOFException // http://stackoverflow.com/questions/15411213/android-httpsurlconnection-eofexception/17791819#17791819 if (Build.VERSION.SDK_INT > 13 && Build.VERSION.SDK_INT < 19) { httpURLConnection.setRequestProperty("Connection", "Close"); } // Set headers for (Map.Entry<String, String> entry : headers.entrySet()) { httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue()); } try { return new HTTPResponse(httpURLConnection.getResponseCode(), httpURLConnection.getHeaderFields(), getContentBody(httpURLConnection), 0); } catch (IOException e) { Log.e(LOG_TAG, "Networking error", e); } finally { httpURLConnection.disconnect(); } return null; }
From source file:com.flyingspaniel.nava.request.Request.java
protected HttpURLConnection prepareConnection(HttpURLConnection conn) { conn.setRequestProperty(ACCEPT_CHARSET, options.getString("acceptCharset", URLEncoding.UTF8_CHARSET)); conn.setInstanceFollowRedirects(options.getBoolean("followRedirect", true)); conn.setUseCaches(options.getBoolean("useCaches", true)); doAuth(conn);// w w w. j av a 2 s .com headersMMap.applyHeadersToConnection(conn); int timeout = options.getInt("timeout", 2000); conn.setConnectTimeout(timeout); conn.setReadTimeout(options.getInt("readTimeout", timeout)); conn.setDoInput(method.doesInput()); conn.setDoOutput(method.doesOutput()); // Since HTTPMethod is an enum with an acceptable protocol, this exception "cannot happen" try { conn.setRequestMethod(method.getMethodName()); } catch (ProtocolException e) { throw new RuntimeException(e); // cannot happen } return conn; }
From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java
/** * Tests request for a unknown user//from w w w . j av a 2s . com * * @throws Exception error */ @Test public void test02RequestUnknownUser() throws Exception { log.trace(">test02RequestUnknownUser()"); // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceReq); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); con.setAllowUserInteraction(false); // POST it con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = con.getOutputStream(); os.write("user=reqtestunknown&password=foo123&keylength=2048".getBytes("UTF-8")); os.close(); final int responseCode = con.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { log.info("ResponseMessage: " + con.getResponseMessage()); assertEquals("Response code", HttpURLConnection.HTTP_OK, responseCode); } log.info("Content-Type: " + con.getContentType()); boolean ok = false; // Some containers return the content type with a space and some // without... if ("text/html;charset=UTF-8".equals(con.getContentType())) { ok = true; } if ("text/html; charset=UTF-8".equals(con.getContentType())) { ok = true; } assertTrue(con.getContentType(), ok); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and PKCS12 requests are small InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); String error = new String(respBytes); int index = error.indexOf("<pre>"); int index2 = error.indexOf("</pre>"); String errormsg = error.substring(index + 5, index2); log.info(errormsg); String expectedErrormsg = "Username: reqtestunknown\nNon existent username. To generate a certificate a valid username and password must be supplied.\n"; assertEquals(expectedErrormsg.replaceAll("\\s", ""), errormsg.replaceAll("\\s", "")); log.trace("<test02RequestUnknownUser()"); }
From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java
/** * Tests request for a wrong password/*from w w w .ja v a 2s.co m*/ * * @throws Exception error */ @Test public void test03RequestWrongPwd() throws Exception { log.trace(">test03RequestWrongPwd()"); setupUser(SecConst.TOKEN_SOFT_P12); // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceReq); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); con.setAllowUserInteraction(false); // POST it con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = con.getOutputStream(); os.write(("user=" + TEST_USERNAME + "&password=foo456&keylength=2048").getBytes("UTF-8")); os.close(); final int responseCode = con.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { log.info("ResponseMessage: " + con.getResponseMessage()); assertEquals("Response code", HttpURLConnection.HTTP_OK, responseCode); } boolean ok = false; // Some containers return the content type with a space and some // without... if ("text/html;charset=UTF-8".equals(con.getContentType())) { ok = true; } if ("text/html; charset=UTF-8".equals(con.getContentType())) { ok = true; } assertTrue(con.getContentType(), ok); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and PKCS12 requests are small InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); String error = new String(respBytes); int index = error.indexOf("<pre>"); int index2 = error.indexOf("</pre>"); String errormsg = error.substring(index + 5, index2); String expectedErrormsg = "Username: " + TEST_USERNAME + "\nWrong username or password"; assertEquals(expectedErrormsg.replaceAll("\\s", ""), errormsg.replaceAll("\\s", "")); log.info(errormsg); log.trace("<test03RequestWrongPwd()"); }
From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java
/** * Tests request with wrong status/* w w w . jav a 2s. c o m*/ * * @throws Exception error */ @Test public void test04RequestWrongStatus() throws Exception { log.trace(">test04RequestWrongStatus()"); setupUser(SecConst.TOKEN_SOFT_P12); setupUserStatus(EndEntityConstants.STATUS_GENERATED); // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceReq); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); con.setAllowUserInteraction(false); // POST it con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = con.getOutputStream(); os.write(("user=" + TEST_USERNAME + "&password=foo456&keylength=2048").getBytes("UTF-8")); os.close(); final int responseCode = con.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { log.info("ResponseMessage: " + con.getResponseMessage()); assertEquals("Response code", HttpURLConnection.HTTP_OK, responseCode); } boolean ok = false; // Some containers return the content type with a space and some // without... if ("text/html;charset=UTF-8".equals(con.getContentType())) { ok = true; } if ("text/html; charset=UTF-8".equals(con.getContentType())) { ok = true; } assertTrue(con.getContentType(), ok); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and PKCS12 requests are small InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); String error = new String(respBytes); int index = error.indexOf("<pre>"); int index2 = error.indexOf("</pre>"); String errormsg = error.substring(index + 5, index2); String expectedErrormsg = "Username: " + TEST_USERNAME + "\nWrong user status! To generate a certificate for a user the user must have status New, Failed or In process.\n"; assertEquals(expectedErrormsg.replaceAll("\\s", ""), errormsg.replaceAll("\\s", "")); log.info(errormsg); log.trace("<test04RequestWrongStatus()"); }
From source file:org.runnerup.export.GarminSynchronizer.java
@Override public Status connect() { Status s = Status.NEED_AUTH;/* w ww . j a va 2s. c o m*/ s.authMethod = Synchronizer.AuthMethod.USER_PASS; if (username == null || password == null) { return s; } if (isConnected) { return Status.OK; } Exception ex = null; HttpURLConnection conn = null; logout(); try { conn = (HttpURLConnection) new URL(CHOOSE_URL).openConnection(); conn.setInstanceFollowRedirects(false); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); Log.e(getName(), "GarminSynchronizer.connect() CHOOSE_URL => code: " + responseCode + ", msg: " + amsg); if (responseCode == HttpStatus.SC_OK) { return connectOld(); } else if (responseCode == HttpStatus.SC_MOVED_TEMPORARILY) { return connectNew(); } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } if (conn != null) conn.disconnect(); s = Synchronizer.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }