List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:org.wso2.msf4j.internal.router.HttpServerTest.java
@Test public void testGzipCompressionWithGzipAccept() throws Exception { HttpURLConnection urlConn = request("/test/v1/gzipfile", HttpMethod.GET); urlConn.addRequestProperty(HttpHeaders.Names.ACCEPT_ENCODING, "gzip"); Assert.assertEquals(HttpResponseStatus.OK.code(), urlConn.getResponseCode()); String contentEncoding = urlConn.getHeaderField(HttpHeaders.Names.CONTENT_ENCODING); Assert.assertTrue("gzip".equalsIgnoreCase(contentEncoding)); InputStream downStream = urlConn.getInputStream(); Assert.assertTrue(IOUtils.toByteArray(downStream).length < IOUtils .toByteArray(Resources.getResource("testJpgFile.jpg").openStream()).length); }
From source file:io.apiman.manager.ui.server.servlets.ApiManagerProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w . j a v a 2 s .co m @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuilder url = new StringBuilder(); String endpoint = getConfig().getManagementApiEndpoint(); if (endpoint == null) { endpoint = getDefaultEndpoint(req); } url.append(endpoint); if (!url.toString().endsWith("/")) { //$NON-NLS-1$ url.append('/'); } String pathInfo = req.getPathInfo(); if (pathInfo != null && pathInfo.startsWith("/")) { //$NON-NLS-1$ url.append(pathInfo.substring(1)); } else { url.append(pathInfo); } String authHeaderValue = null; ApiAuthType authType = getConfig().getManagementApiAuthType(); switch (authType) { case basic: { String username = getConfig().getManagementApiAuthUsername(); String password = getConfig().getManagementApiAuthPassword(); String encoded = base64Encode(username + ":" + password); //$NON-NLS-1$ authHeaderValue = "Basic " + encoded; //$NON-NLS-1$ break; } case authToken: { ITokenGenerator tokenGenerator = getTokenGenerator(); BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req); String token = creds.getToken(); authHeaderValue = "AUTH-TOKEN " + token; //$NON-NLS-1$ break; } case bearerToken: { ITokenGenerator tokenGenerator = getTokenGenerator(); BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req); String token = creds.getToken(); authHeaderValue = "Bearer " + token; //$NON-NLS-1$ break; } case samlBearerToken: { ITokenGenerator tokenGenerator = getTokenGenerator(); BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req); String token = creds.getToken(); // TODO base64 decode the token, then re-encode it with "SAML-BEARER-TOKEN:" authHeaderValue = "Basic SAML-BEARER-TOKEN:" + token; //$NON-NLS-1$ break; } } URL remoteUrl = new URL(url.toString()); HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection(); InputStream remoteIS = null; OutputStream responseOS = null; try { if (authHeaderValue != null) { remoteConn.setRequestProperty("Authorization", authHeaderValue); //$NON-NLS-1$ } remoteConn.connect(); Map<String, List<String>> headerFields = remoteConn.getHeaderFields(); for (String headerName : headerFields.keySet()) { if (headerName == null) { continue; } if (EXCLUDE_HEADERS.contains(headerName)) { continue; } String headerValue = remoteConn.getHeaderField(headerName); resp.setHeader(headerName, headerValue); if (url.toString().contains("apiregistry")) { //$NON-NLS-1$ String type = "json"; //$NON-NLS-1$ if (url.toString().endsWith("xml")) { //$NON-NLS-1$ type = "xml"; //$NON-NLS-1$ } resp.setHeader("Content-Disposition", "attachment; filename=api-registry." + type); //$NON-NLS-1$ //$NON-NLS-2$ } } resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-1$ //$NON-NLS-2$ remoteIS = remoteConn.getInputStream(); responseOS = resp.getOutputStream(); IOUtils.copy(remoteIS, responseOS); resp.flushBuffer(); } catch (Exception e) { resp.sendError(500, e.getMessage()); } finally { IOUtils.closeQuietly(responseOS); IOUtils.closeQuietly(remoteIS); } }
From source file:org.apache.tez.runtime.library.shuffle.common.Fetcher.java
private void validateConnectionResponse(HttpURLConnection connection, URL url, String msgToEncode, String encHash) throws IOException { int rc = connection.getResponseCode(); if (rc != HttpURLConnection.HTTP_OK) { throw new IOException( "Got invalid response code " + rc + " from " + url + ": " + connection.getResponseMessage()); }//from w w w . j av a 2 s . c om if (!ShuffleHeader.DEFAULT_HTTP_HEADER_NAME .equals(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_NAME)) || !ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION .equals(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_VERSION))) { throw new IOException("Incompatible shuffle response version"); } // get the replyHash which is HMac of the encHash we sent to the server String replyHash = connection.getHeaderField(SecureShuffleUtils.HTTP_HEADER_REPLY_URL_HASH); if (replyHash == null) { throw new IOException("security validation of TT Map output failed"); } if (LOG.isDebugEnabled()) { LOG.debug("url=" + msgToEncode + ";encHash=" + encHash + ";replyHash=" + replyHash); } // verify that replyHash is HMac of encHash SecureShuffleUtils.verifyReply(replyHash, encHash, shuffleSecret); LOG.info("for url=" + msgToEncode + " sent hash and receievd reply"); }
From source file:org.apache.olingo.fit.tecsvc.http.AcceptHeaderAcceptCharsetHeaderITCase.java
@Test public void unsupportedAcceptHeaderWithSupportedAcceptCharsetHeader() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf8;q=0.1"); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;charset=iso8859-1"); connection.connect();/*from ww w.ja va 2 s. c o m*/ assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE)); ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE)); assertEquals("application", contentType.getType()); assertEquals("json", contentType.getSubtype()); assertEquals(3, contentType.getParameters().size()); assertEquals("0.1", contentType.getParameter("q")); assertEquals("minimal", contentType.getParameter("odata.metadata")); assertEquals("utf8", contentType.getParameter("charset")); final String content = IOUtils.toString(connection.getInputStream()); assertNotNull(content); }
From source file:com.boxupp.utilities.PuppetUtilities.java
public StatusBean downloadModule(JsonNode moduleData) { Gson searchModuleData = new GsonBuilder().setDateFormat("yyyy'-'MM'-'dd HH':'mm':'ss").create(); SearchModuleBean searchModuleBean = searchModuleData.fromJson(moduleData.toString(), SearchModuleBean.class); String fileURL = CommonProperties.getInstance().getPuppetForgeDownloadAPIPath() + searchModuleBean.getCurrent_release().getFile_uri(); StatusBean statusBean = new StatusBean(); URL url = null;/*from w w w.ja va 2 s.c om*/ int responseCode = 0; HttpURLConnection httpConn = null; String fileSeparator = OSProperties.getInstance().getOSFileSeparator(); String moduleDirPath = constructModuleDirectory() + fileSeparator; checkIfDirExists(new File(constructManifestsDirectory())); checkIfDirExists(new File(moduleDirPath)); try { url = new URL(fileURL); httpConn = (HttpURLConnection) url.openConnection(); responseCode = httpConn.getResponseCode(); // always check HTTP response code first if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = ""; String disposition = httpConn.getHeaderField("Content-Disposition"); String contentType = httpConn.getContentType(); int contentLength = httpConn.getContentLength(); if (disposition != null) { int index = disposition.indexOf("filename="); if (index > 0) { fileName = disposition.substring(index + 9, disposition.length()); } } else { fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); } InputStream inputStream = httpConn.getInputStream(); String saveFilePath = moduleDirPath + fileName; FileOutputStream outputStream = new FileOutputStream(saveFilePath); int bytesRead = -1; byte[] buffer = new byte[4096]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); extrectFile(saveFilePath, moduleDirPath, searchModuleBean.getModuleName()); File file = new File(saveFilePath); file.delete(); } else { logger.error("No file to download. Server replied HTTP code: " + responseCode); } httpConn.disconnect(); statusBean.setStatusCode(0); statusBean.setStatusMessage(" Module Downloaded successfully "); } catch (IOException e) { logger.error("Error in loading module :" + e.getMessage()); statusBean.setStatusCode(1); statusBean.setStatusMessage("Error in loading module :" + e.getMessage()); } statusBean = PuppetModuleDAOManager.getInstance().create(moduleData); return statusBean; }
From source file:org.apache.olingo.fit.tecsvc.http.AcceptHeaderAcceptCharsetHeaderITCase.java
@Test public void multipleValuesInAcceptCharsetHeader1() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf-8;q=0.1,iso-8859-1,unicode-1-1"); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json"); connection.connect();//w w w .j ava 2 s . co m assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE)); ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE)); assertEquals("application", contentType.getType()); assertEquals("json", contentType.getSubtype()); assertEquals(3, contentType.getParameters().size()); assertEquals("minimal", contentType.getParameter("odata.metadata")); assertEquals("utf-8", contentType.getParameter("charset")); assertEquals("0.1", contentType.getParameter("q")); final String content = IOUtils.toString(connection.getInputStream()); assertNotNull(content); }
From source file:tree.love.providers.downloads.DownloadThread.java
/** * Read headers from the HTTP response and store them into local state. *//*from w w w . j a v a 2 s . co m*/ private void readResponseHeaders(State state, HttpURLConnection conn) throws StopRequestException { state.mContentDisposition = conn.getHeaderField("Content-Disposition"); state.mContentLocation = conn.getHeaderField("Content-Location"); if (state.mMimeType == null) { state.mMimeType = normalizeMimeType(conn.getContentType()); } state.mHeaderETag = conn.getHeaderField("ETag"); final String transferEncoding = conn.getHeaderField("Transfer-Encoding"); if (transferEncoding == null) { state.mContentLength = getHeaderFieldLong(conn, "Content-Length", -1); } else { Log.i(TAG, "Ignoring Content-Length since Transfer-Encoding is also defined"); state.mContentLength = -1; } state.mTotalBytes = state.mContentLength; mInfo.mTotalBytes = state.mContentLength; final boolean noSizeInfo = state.mContentLength == -1 && (transferEncoding == null || !transferEncoding.equalsIgnoreCase("chunked")); if (!mInfo.mNoIntegrity && noSizeInfo) { throw new StopRequestException(STATUS_CANNOT_RESUME, "can't know size of download, giving up"); } }
From source file:org.apache.olingo.fit.tecsvc.http.AcceptHeaderAcceptCharsetHeaderITCase.java
@Test public void validAcceptCharsetHeader() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf-8;q=0.1"); connection.setRequestProperty(HttpHeader.ACCEPT, ContentType.APPLICATION_JSON.toContentTypeString()); connection.connect();//from w ww. ja v a 2 s. c om assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE)); ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE)); assertEquals("application", contentType.getType()); assertEquals("json", contentType.getSubtype()); assertEquals(3, contentType.getParameters().size()); assertEquals("0.1", contentType.getParameter("q")); assertEquals("minimal", contentType.getParameter("odata.metadata")); assertEquals("utf-8", contentType.getParameter("charset")); final String content = IOUtils.toString(connection.getInputStream()); assertNotNull(content); }
From source file:org.callimachusproject.test.WebResource.java
public WebResource create(Map<String, String> headers, String type, byte[] body) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection(); con.setRequestMethod("POST"); for (Map.Entry<String, String> e : headers.entrySet()) { con.setRequestProperty(e.getKey(), e.getValue()); }//from w w w. ja v a 2 s . co m con.setRequestProperty("Content-Type", type); con.setDoOutput(true); OutputStream out = con.getOutputStream(); try { out.write(body); } finally { out.close(); } Assert.assertEquals(con.getResponseMessage(), 201, con.getResponseCode()); String header = con.getHeaderField("Location"); Assert.assertNotNull(header); return ref(header); }
From source file:org.appcelerator.titanium.util.TiUIHelper.java
/** * To get the redirected Uri/*from w ww .j a v a 2 s. com*/ * @param Uri */ public static Uri getRedirectUri(Uri mUri) throws MalformedURLException, IOException { if (!TiC.HONEYCOMB_OR_GREATER && ("http".equals(mUri.getScheme()) || "https".equals(mUri.getScheme()))) { // Media player doesn't handle redirects, try to follow them // here. (Redirects work fine without this in ICS.) while (true) { // java.net.URL doesn't handle rtsp if (mUri.getScheme() != null && mUri.getScheme().equals("rtsp")) break; URL url = new URL(mUri.toString()); HttpURLConnection cn = (HttpURLConnection) url.openConnection(); cn.setInstanceFollowRedirects(false); String location = cn.getHeaderField("Location"); if (location != null) { String host = mUri.getHost(); int port = mUri.getPort(); String scheme = mUri.getScheme(); mUri = Uri.parse(location); if (mUri.getScheme() == null) { // Absolute URL on existing host/port/scheme if (scheme == null) { scheme = "http"; } String authority = port == -1 ? host : host + ":" + port; mUri = mUri.buildUpon().scheme(scheme).encodedAuthority(authority).build(); } } else { break; } } } return mUri; }