List of usage examples for java.net HttpURLConnection getHeaderFields
public Map<String, List<String>> getHeaderFields()
From source file:com.spotify.helios.client.DefaultRequestDispatcher.java
@Override public ListenableFuture<Response> request(final URI uri, final String method, final byte[] entityBytes, final Map<String, List<String>> headers) { return executorService.submit(new Callable<Response>() { @Override// w ww . ja v a 2 s . co m public Response call() throws Exception { final HttpURLConnection connection = connect(uri, method, entityBytes, headers); final int status = connection.getResponseCode(); final InputStream rawStream; if (status / 100 != 2) { rawStream = connection.getErrorStream(); } else { rawStream = connection.getInputStream(); } final boolean gzip = isGzipCompressed(connection); final InputStream stream = gzip ? new GZIPInputStream(rawStream) : rawStream; final ByteArrayOutputStream payload = new ByteArrayOutputStream(); if (stream != null) { int n; byte[] buffer = new byte[4096]; while ((n = stream.read(buffer, 0, buffer.length)) != -1) { payload.write(buffer, 0, n); } } URI realUri = connection.getURL().toURI(); if (log.isTraceEnabled()) { log.trace("rep: {} {} {} {} {} gzip:{}", method, realUri, status, payload.size(), decode(payload), gzip); } else { log.debug("rep: {} {} {} {} gzip:{}", method, realUri, status, payload.size(), gzip); } return new Response(method, uri, status, payload.toByteArray(), Collections.unmodifiableMap(Maps.newHashMap(connection.getHeaderFields()))); } private boolean isGzipCompressed(final HttpURLConnection connection) { final List<String> encodings = connection.getHeaderFields().get("Content-Encoding"); if (encodings == null) { return false; } for (String encoding : encodings) { if ("gzip".equals(encoding)) { return true; } } return false; } }); }
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 . j a va 2 s.co m 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.androidex.volley.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError, IOException { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());/*from w ww . ja v a 2 s.c o m*/ map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); if (!TextUtils.isEmpty(mUserAgent)) { connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent); } for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } if (request instanceof MultiPartRequest) { setConnectionParametersForMultipartRequest(connection, request); } else { setConnectionParametersForRequest(connection, request); } // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could // not be retrieved. // Signal to the caller that something was wrong with the // connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:com.daidiansha.acarry.control.network.core.volley.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError, IOException { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());/*from w w w . java 2s . c om*/ map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); if (!TextUtils.isEmpty(mUserAgent)) { connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent); } for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } if (request instanceof MultiPartRequest) { setConnectionParametersForMultipartRequest(connection, (MultiPartRequest) request); } else { setConnectionParametersForRequest(connection, request); } // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could // not be retrieved. // Signal to the caller that something was wrong with the // connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:com.volley.air.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError, IOException { String url = request.getUrl(); HashMap<String, String> map = new HashMap<>(); map.putAll(request.getHeaders());//from w w w. j a v a2s. c o m map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); if (!TextUtils.isEmpty(mUserAgent)) { connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent); } for (Entry<String, String> entry : map.entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); } if (request instanceof MultiPartRequest) { setConnectionParametersForMultipartRequest(connection, request); } else { setConnectionParametersForRequest(connection, request); } // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could // not be retrieved. // Signal to the caller that something was wrong with the // connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:com.facebook.RequestTests.java
@LargeTest public void testExecuteSingleGetUsingHttpURLConnection() throws IOException { Bundle parameters = new Bundle(); parameters.putString("fields", "location"); GraphRequest request = new GraphRequest(AccessToken.getCurrentAccessToken(), "TourEiffel", parameters, null);/* w ww .j a v a2s . com*/ HttpURLConnection connection = GraphRequest.toHttpConnection(request); assertEquals("gzip", connection.getRequestProperty("Content-Encoding")); assertEquals("application/x-www-form-urlencoded", connection.getRequestProperty("Content-Type")); List<GraphResponse> responses = GraphRequest.executeConnectionAndWait(connection, Arrays.asList(new GraphRequest[] { request })); assertNotNull(responses); assertEquals(1, responses.size()); GraphResponse response = responses.get(0); assertTrue(response != null); assertTrue(response.getError() == null); assertNotNull(response.getJSONObject()); assertNotNull(response.getRawResponse()); JSONObject graphPlace = response.getJSONObject(); assertEquals("Paris", graphPlace.optJSONObject("location").optString("city")); // Make sure calling code can still access HTTP headers and call disconnect themselves. int code = connection.getResponseCode(); assertEquals(200, code); assertTrue(connection.getHeaderFields().keySet().contains("Content-Type")); connection.disconnect(); }
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 a v a2 s . 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:org.aselect.authspserver.authsp.delegator.HTTPSTrustAllDelegate.java
public int authenticate(Map<String, String> requestparameters, Map<String, List<String>> responseparameters) throws DelegateException { String sMethod = "authenticate"; int iReturnCode = -1; AuthSPSystemLogger _systemLogger;//w w w.java 2s . com _systemLogger = AuthSPSystemLogger.getHandle(); _systemLogger.log(Level.FINEST, sModule, sMethod, "requestparameters=" + requestparameters + " , responseparameters=" + responseparameters); StringBuffer data = new StringBuffer(); String sResult = ""; ; try { final String EQUAL_SIGN = "="; final String AMPERSAND = "&"; final String NEWLINE = "\n"; for (String key : requestparameters.keySet()) { data.append(URLEncoder.encode(key, "UTF-8")); data.append(EQUAL_SIGN).append(URLEncoder.encode( ((String) requestparameters.get(key) == null) ? "" : (String) requestparameters.get(key), "UTF-8")); data.append(AMPERSAND); } if (data.length() > 0) data.deleteCharAt(data.length() - 1); // remove last AMPERSAND // data.append(NEWLINE).append(NEWLINE); // _systemLogger.log(Level.FINE, sModule, sMethod, "url=" + url.toString() + " data={" + data.toString() + "}"); // no data shown in production environment ///////////// HERE WE DO THE TRUST ALL STUFF /////////////////////////////// // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } public X509Certificate[] getAcceptedIssuers() { return null; } } }; ///////////// HERE WE DO THE TRUST ALL STUFF /////////////////////////////// // Install the all-trusting trust manager final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); ///////////// HERE WE DO THE TRUST ALL STUFF /////////////////////////////// // Tell the url connection object to use our socket factory which bypasses security checks ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory); ///////////// HERE WE DO THE TRUST ALL STUFF /////////////////////////////// // Basic authentication if (this.delegateuser != null) { byte[] bEncoded = Base64 .encodeBase64((this.delegateuser + ":" + (delegatepassword == null ? "" : delegatepassword)) .getBytes("UTF-8")); String encoded = new String(bEncoded, "UTF-8"); conn.setRequestProperty("Authorization", "Basic " + encoded); _systemLogger.log(Level.FINEST, sModule, sMethod, "Using basic authentication, user=" + this.delegateuser); } // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // They (the delegate party) don't accept charset !! conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data.toString()); wr.flush(); wr.close(); // Get the response iReturnCode = conn.getResponseCode(); Map<String, List<String>> hFields = conn.getHeaderFields(); _systemLogger.log(Level.FINEST, sModule, sMethod, "response=" + iReturnCode); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; // Still to decide on response protocol while ((line = rd.readLine()) != null) { sResult += line; } _systemLogger.log(Level.INFO, sModule, sMethod, "sResult=" + sResult); // Parse response here // For test return request parameters // responseparameters.putAll(requestparameters); responseparameters.putAll(hFields); rd.close(); } catch (IOException e) { _systemLogger.log(Level.INFO, sModule, sMethod, "Error while reading sResult data, maybe no data at all. sResult=" + sResult); } catch (NumberFormatException e) { throw new DelegateException("Sending authenticate request, using \'" + this.url.toString() + "\' failed due to number format exception! " + e.getMessage(), e); } catch (Exception e) { throw new DelegateException("Sending authenticate request, using \'" + this.url.toString() + "\' failed (progress=" + iReturnCode + ")! " + e.getMessage(), e); } return iReturnCode; }
From source file:com.baseproject.volley.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());//from ww w.ja va2s.c o m map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException(Util.buildHttpErrorMsg("failed", -1, "URL blocked by rewriter: " + url)); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); // if (responseCode == -1) { // // -1 is returned by getResponseCode() if the response code could not be retrieved. // // Signal to the caller that something was wrong with the connection. // throw new IOException("Could not retrieve response code from HttpUrlConnection."); // } if (responseCode != HttpStatus.SC_NOT_MODIFIED && responseCode != HttpURLConnection.HTTP_OK) { InputStream in = null; try { in = connection.getErrorStream(); } catch (Exception e) { e.printStackTrace(); } if (in == null) { throw new IOException(Util.buildHttpErrorMsg("failed", responseCode, "unknown")); } else { throw new IOException(Util.convertStreamToString(in)); } } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { if (header.getKey().equals("Set-Cookie")) { List<String> cookieValue = header.getValue(); for (String c : cookieValue) { Header h = new BasicHeader(header.getKey(), c); response.addHeader(h); } } else { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } } return response; }
From source file:it.greenvulcano.gvesb.adapter.http.mapping.ForwardHttpServletMapping.java
@SuppressWarnings("deprecation") @Override//from w w w . j a v a2 s.c o m public void handleRequest(String methodName, HttpServletRequest req, HttpServletResponse resp) throws InboundHttpResponseException { logger.debug("BEGIN forward: " + req.getRequestURI()); final HttpURLConnection httpConnection = (HttpURLConnection) connection; ; try { httpConnection.setRequestMethod(methodName); httpConnection.setReadTimeout(soTimeout); httpConnection.setDoInput(true); httpConnection.setDoOutput(true); if (dump) { StringBuffer sb = new StringBuffer(); DumpUtils.dump(req, sb); logger.info(sb.toString()); } String mapping = req.getPathInfo(); if (mapping == null) { mapping = "/"; } String destPath = contextPath + mapping; String queryString = req.getQueryString(); if (queryString != null) { destPath += "?" + queryString; } if (!destPath.startsWith("/")) { destPath = "/" + destPath; } logger.info("Resulting QueryString: " + destPath); Collections.list(req.getHeaderNames()).forEach(headerName -> { httpConnection.setRequestProperty(headerName, Collections.list(req.getHeaders(headerName)).stream().collect(Collectors.joining(";"))); }); if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) { httpConnection.setDoOutput(true); IOUtils.copy(req.getInputStream(), httpConnection.getOutputStream()); } httpConnection.connect(); int status = httpConnection.getResponseCode(); resp.setStatus(status, httpConnection.getResponseMessage()); httpConnection.getHeaderFields().entrySet().stream().forEach(header -> { resp.addHeader(header.getKey(), header.getValue().stream().collect(Collectors.joining(";"))); }); ByteArrayOutputStream bodyOut = new ByteArrayOutputStream(); IOUtils.copy(httpConnection.getInputStream(), bodyOut); OutputStream out = resp.getOutputStream(); out.write(bodyOut.toByteArray()); //IOUtils.copy(method.getResponseBodyAsStream(), out); out.flush(); out.close(); if (dump) { StringBuffer sb = new StringBuffer(); DumpUtils.dump(resp, bodyOut, sb); logger.info(sb.toString()); } } catch (Exception exc) { logger.error("ERROR on forwarding: " + req.getRequestURI(), exc); throw new InboundHttpResponseException("GV_CALL_SERVICE_ERROR", new String[][] { { "message", exc.getMessage() } }, exc); } finally { try { if (httpConnection != null) { httpConnection.disconnect(); } } catch (Exception exc) { logger.warn("Error while releasing connection", exc); } logger.debug("END forward: " + req.getRequestURI()); } }