List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:org.omegat.gui.glossary.taas.TaaSClient.java
/** * Check content type of response.// ww w.j a v a 2 s . com */ void checkXMLUTF8ContentType(HttpURLConnection conn) throws FormatError { String contentType = conn.getHeaderField("Content-Type"); if (contentType == null) { throw new FormatError("Empty Content-Type header"); } String ct = contentType.replace(" ", "").toLowerCase(); if (!"text/xml;charset=utf-8".equals(ct) && !"application/xml;charset=utf-8".equals(ct)) { throw new FormatError("Wrong Content-Type header: " + contentType); } }
From source file:com.bytelightning.opensource.pokerface.ProxySpecificTest.java
/** * Create a client request to PokerFace and verify that it proxied to the SunHttpServer correctly. *//* w ww. j a va 2 s .c om*/ @Test public void testViaHeader() throws IOException { URL obj = new URL("http://localhost:8080/index.html"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); int responseCode = con.getResponseCode(); Assert.assertEquals("Valid reponse code", 200, responseCode); String hdrField = con.getHeaderField("Via"); Assert.assertNotNull("Received a 'via' header", hdrField); Assert.assertEquals("Received a valid 'via' header", "HTTP/1.1 PokerFace/" + Utils.Version, hdrField); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); while (in.readLine() != null) ; in.close(); }
From source file:org.ejbca.ui.web.pub.HttpMethodsTest.java
/** Test the publicweb.war module. */ @Test// w w w.ja v a 2 s .c o m public void testPublicWebSecurityHeaders() throws Exception { // Check for X-FRAME-OPTIONS headers HttpURLConnection con = getHttpURLConnection(httpBaseUrl + "/ejbca/index.jsp"); String xframe = con.getHeaderField("X-FRAME-OPTIONS"); String csp = con.getHeaderField("content-security-policy"); String xcsp = con.getHeaderField("x-content-security-policy"); con.disconnect(); assertNotNull("Public web should return X-FRAME-OPTIONS header", xframe); assertNotNull("Public web page should return content-security-policy header", csp); assertNotNull("Public web page should return x-content-security-policy header", xcsp); assertEquals("Public web should return X-FRAME-OPTIONS DENY", "DENY", xframe); assertEquals( "Public web page should return csp default-src 'none'; object-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self'; frame-src 'self'; form-action 'self'; reflected-xss block", "default-src 'none'; object-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self'; frame-src 'self'; form-action 'self'; reflected-xss block", csp); assertEquals( "Public web page should return xcsp default-src 'none'; object-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self'; frame-src 'self'; form-action 'self'; reflected-xss block", "default-src 'none'; object-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self'; frame-src 'self'; form-action 'self'; reflected-xss block", xcsp); }
From source file:com.breadwallet.tools.util.JsonParser.java
private static String callURL(String myURL) { // System.out.println("Requested URL_EA:" + myURL); StringBuilder sb = new StringBuilder(); HttpURLConnection urlConn = null; InputStreamReader in = null;//from w w w . j ava2s.com try { URL url = new URL(myURL); urlConn = (HttpURLConnection) url.openConnection(); int versionNumber = 0; MainActivity app = MainActivity.app; if (app != null) { try { PackageInfo pInfo = null; pInfo = app.getPackageManager().getPackageInfo(app.getPackageName(), 0); versionNumber = pInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } int stringId = 0; String appName = ""; if (app != null) { stringId = app.getApplicationInfo().labelRes; appName = app.getString(stringId); } String message = String.format(Locale.getDefault(), "%s/%d/%s", appName.isEmpty() ? "breadwallet" : appName, versionNumber, System.getProperty("http.agent")); urlConn.setRequestProperty("User-agent", message); urlConn.setReadTimeout(60 * 1000); String strDate = urlConn.getHeaderField("date"); if (strDate == null || app == null) { Log.e(TAG, "callURL: strDate == null!!!"); } else { @SuppressWarnings("deprecation") long date = Date.parse(strDate) / 1000; SharedPreferencesManager.putSecureTime(app, date); Assert.assertTrue(date != 0); } if (urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } assert in != null; in.close(); } catch (Exception e) { return null; } return sb.toString(); }
From source file:org.apache.olingo.fit.tecsvc.http.BasicStreamITCase.java
@Test public void streamESStreamXml() throws Exception { URL url = new URL(SERVICE_URI + "ESStream?$format=xml"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.connect();//from w w w . ja v a2s .c o m assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.APPLICATION_XML, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE))); final String content = IOUtils.toString(connection.getInputStream()); System.out.println(content); assertTrue(content.contains("<m:element>Streamed-Employee1@company.example</m:element>" + "<m:element>Streamed-Employee2@company.example</m:element>" + "<m:element>Streamed-Employee3@company.example</m:element>")); assertTrue(content.contains("<d:PropertyString>TEST 1->streamed</d:PropertyString>")); assertTrue(content.contains("<d:PropertyString>TEST 2->streamed</d:PropertyString>")); }
From source file:org.apache.nifi.minifi.c2.provider.delegating.DelegatingConfigurationProvider.java
@Override public Configuration getConfiguration(String contentType, Integer version, Map<String, List<String>> parameters) throws ConfigurationProviderException { HttpURLConnection remoteC2ServerConnection = null; try {/*w ww .j a v a2s.c om*/ if (version == null) { remoteC2ServerConnection = getDelegateConnection(contentType, parameters); version = Integer.parseInt(remoteC2ServerConnection.getHeaderField("X-Content-Version")); if (logger.isDebugEnabled()) { logger.debug("Got current version " + version + " from upstream."); } } ConfigurationCacheFileInfo cacheFileInfo = configurationCache.getCacheFileInfo(contentType, parameters); WriteableConfiguration configuration = cacheFileInfo.getConfiguration(version); if (!configuration.exists()) { if (remoteC2ServerConnection == null) { remoteC2ServerConnection = getDelegateConnection(contentType, parameters); } try (InputStream inputStream = remoteC2ServerConnection.getInputStream(); OutputStream outputStream = configuration.getOutputStream()) { IOUtils.copy(inputStream, outputStream); } catch (IOException e) { throw new ConfigurationProviderException("Unable to copy remote configuration to cache.", e); } } return configuration; } finally { if (remoteC2ServerConnection != null) { remoteC2ServerConnection.disconnect(); } } }
From source file:org.bibsonomy.util.WebUtils.java
/** * Sends a request to the given URL and checks, if it contains a redirect. * If it does, returns the redirect URL. Otherwise, returns null. * This is done up to {@value #MAX_REDIRECT_COUNT}-times until the final page is reached. * // w w w. java 2s . c o m * * * @param url * @return - The redirect URL. */ public static URL getRedirectUrl(final URL url) { try { URL internalUrl = url; URL previousUrl = null; int redirectCtr = 0; while (internalUrl != null && redirectCtr < MAX_REDIRECT_COUNT) { redirectCtr++; final HttpURLConnection urlConn = (HttpURLConnection) internalUrl.openConnection(); urlConn.setAllowUserInteraction(false); urlConn.setDoInput(true); urlConn.setDoOutput(false); urlConn.setUseCaches(false); urlConn.setInstanceFollowRedirects(false); /* * set user agent (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) since some * pages require it to download content. */ urlConn.setRequestProperty(USER_AGENT_HEADER_NAME, USER_AGENT_PROPERTY_VALUE); urlConn.connect(); // get URL to redirected resource previousUrl = internalUrl; try { internalUrl = new URL(urlConn.getHeaderField(LOCATION)); } catch (final MalformedURLException e) { internalUrl = null; } urlConn.disconnect(); } return previousUrl; } catch (final IOException e) { e.printStackTrace(); return null; } }
From source file:org.ejbca.ui.web.pub.HttpMethodsTest.java
/** Test the adminweb.war module that it returns X-FRAME-OPTIONS on the error page. */ @Test/* w w w . j a v a2s . co m*/ public void testAdminWebXFrameOptionsOnError() throws Exception { // Check for X-FRAME-OPTIONS headers // We will not be able to actually read this url, because we use port 8080, and adminweb requires client authentication, // But EJBCA will still return a "blank" page with the correct http header. HttpURLConnection con = getHttpURLConnection(httpBaseUrl + "/ejbca/adminweb/index.jsp"); String xframe = con.getHeaderField("X-FRAME-OPTIONS"); String csp = con.getHeaderField("content-security-policy"); String xcsp = con.getHeaderField("x-content-security-policy"); con.disconnect(); assertNotNull("Admin web error page should return X-FRAME-OPTIONS header", xframe); assertNotNull("Admin web error page should return content-security-policy header", csp); assertNotNull("Admin web error page should return x-content-security-policy header", xcsp); assertEquals("Admin web error page should return X-FRAME-OPTIONS SAMEORIGIN", "SAMEORIGIN", xframe); assertEquals( "Admin web error page should return csp default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self'; img-src 'self'; frame-src 'self'; reflected-xss block", "default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self'; img-src 'self'; frame-src 'self'; reflected-xss block", csp); assertEquals( "Admin web error page should return x-csp default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self'; img-src 'self'; frame-src 'self'; reflected-xss block", "default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self'; img-src 'self'; frame-src 'self'; reflected-xss block", xcsp); }
From source file:com.micro.utils.F.java
/** * ???xx.??.//from ww w. ja v a 2 s.com * @param connection * @return ?? */ public static String getRealFileName(HttpURLConnection connection) { String name = null; try { if (connection == null) { return name; } if (connection.getResponseCode() == 200) { for (int i = 0;; i++) { String mime = connection.getHeaderField(i); if (mime == null) { break; } // "Content-Disposition","attachment; filename=1.txt" // Content-Length if ("content-disposition".equals(connection.getHeaderFieldKey(i).toLowerCase())) { Matcher m = Pattern.compile(".*filename=(.*)").matcher(mime.toLowerCase()); if (m.find()) { return m.group(1).replace("\"", ""); } } } } } catch (Exception e) { e.printStackTrace(); L.E("???"); } return name; }
From source file:com.gallatinsystems.common.util.S3Util.java
public static boolean put(String bucketName, String objectKey, byte[] data, String contentType, boolean isPublic, String awsAccessId, String awsSecretKey) throws IOException { final byte[] md5Raw = MD5Util.md5(data); final String md5Base64 = Base64.encodeBase64String(md5Raw).trim(); final String md5Hex = MD5Util.toHex(md5Raw); final String date = getDate(); final String payloadStr = isPublic ? PUT_PAYLOAD_PUBLIC : PUT_PAYLOAD_PRIVATE; final String payload = String.format(payloadStr, md5Base64, contentType, date, bucketName, objectKey); final String signature = MD5Util.generateHMAC(payload, awsSecretKey); final URL url = new URL(String.format(S3_URL, bucketName, objectKey)); OutputStream out = null;//from w w w .j a v a2 s . c o m HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-MD5", md5Base64); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Date", date); if (isPublic) { // If we don't send this header, the object will be private by default conn.setRequestProperty("x-amz-acl", "public-read"); } conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature); out = new BufferedOutputStream(conn.getOutputStream()); IOUtils.copy(new ByteArrayInputStream(data), out); out.flush(); int status = conn.getResponseCode(); if (status != 200 && status != 201) { log.severe("Error uploading file: " + url.toString()); log.severe(IOUtils.toString(conn.getInputStream())); return false; } String etag = conn.getHeaderField("ETag"); etag = etag != null ? etag.replaceAll("\"", "") : null;// Remove quotes if (!md5Hex.equals(etag)) { log.severe("ETag comparison failed. Response ETag: " + etag + "Locally computed MD5: " + md5Hex); return false; } return true; } finally { if (conn != null) { conn.disconnect(); } IOUtils.closeQuietly(out); } }