List of usage examples for java.net HttpURLConnection getHeaderFields
public Map<String, List<String>> getHeaderFields()
From source file:net.solarnetwork.node.setup.web.SolarInHttpProxy.java
/** * Proxy an HTTP request to SolarIn and return the result on a given HTTP * response.// ww w .j av a2 s . c o m * * @param request * the request to proxy * @param response * the response to return the proxy response to * @throws IOException * if an IO error occurs */ @RequestMapping(value = { "/api/v1/sec/location", "/api/v1/sec/location/price", "/api/v1/sec/location/weather" }, method = RequestMethod.GET) public void proxy(HttpServletRequest request, HttpServletResponse response) throws IOException { String context = request.getContextPath(); String path = request.getRequestURI(); if (path.startsWith(context)) { path = path.substring(context.length()); } String query = request.getQueryString(); String url = getIdentityService().getSolarInBaseUrl() + path; if (query != null) { url += '?' + query; } String accept = request.getHeader("Accept"); if (accept == null) { accept = ACCEPT_JSON; } try { URLConnection conn = getURLConnection(url, request.getMethod(), accept); if (conn instanceof HttpURLConnection) { final HttpURLConnection httpConn = (HttpURLConnection) conn; for (Map.Entry<String, List<String>> me : httpConn.getHeaderFields().entrySet()) { final String headerName = me.getKey(); if (headerName == null) { continue; } for (String val : me.getValue()) { response.addHeader(headerName, val); } } final String msg = httpConn.getResponseMessage(); if (msg != null && !msg.equalsIgnoreCase("OK")) { response.sendError(httpConn.getResponseCode(), msg); } else { response.setStatus(httpConn.getResponseCode()); } } FileCopyUtils.copy(conn.getInputStream(), response.getOutputStream()); response.flushBuffer(); } catch (IOException e) { log.debug("Error proxying SolarIn URL [{}]", url, e); response.sendError(502, "Problem communicating with SolarIn: " + e.getMessage()); } }
From source file:org.codehaus.httpcache4j.urlconnection.URLConnectionResponseResolver.java
private Headers getResponseHeaders(HttpURLConnection connection) { Headers headers = new Headers(); Map<String, List<String>> headerFields = connection.getHeaderFields(); for (Map.Entry<String, List<String>> entry : headerFields.entrySet()) { for (String headerValue : entry.getValue()) { if (entry.getKey() != null) { headers = headers.add(entry.getKey(), headerValue); }//from www. j a v a2 s . co m } } return headers; }
From source file:org.eclipse.ecf.internal.provider.etcd.protocol.EtcdRequest.java
protected EtcdResponse getResponseOrError(HttpURLConnection conn) throws IOException, JSONException { try {//from w w w . j ava 2 s .co m return new EtcdSuccessResponse(readStream(conn.getInputStream()), conn.getHeaderFields()); } catch (IOException e) { return new EtcdErrorResponse(readStream(conn.getErrorStream()), conn.getHeaderFields()); } }
From source file:org.apache.falcon.regression.ProcessLibPathLoadTest.java
/** * Function to download jar at remote public location. * @param urlString public location from where jar is to be downloaded * filename is the location where the jar is to be saved * @throws Exception/*from w w w. j a v a 2s .c om*/ */ private void saveUrlToFile(String urlString) throws IOException { URL url = new URL(urlString); String link; HttpURLConnection http = (HttpURLConnection) url.openConnection(); Map<String, List<String>> header = http.getHeaderFields(); while (isRedirected(header)) { link = header.get("Location").get(0); url = new URL(link); http = (HttpURLConnection) url.openConnection(); header = http.getHeaderFields(); } InputStream input = http.getInputStream(); byte[] buffer = new byte[4096]; int n; OutputStream output = new FileOutputStream(new File(filename)); while ((n = input.read(buffer)) != -1) { output.write(buffer, 0, n); } output.close(); }
From source file:com.github.reverseproxy.ReverseProxyJettyHandler.java
private void writeResponse(URLConnection urlConn, HttpServletResponse response) throws IOException { HttpURLConnection urlConnection = (HttpURLConnection) urlConn; Map<String, List<String>> headers = urlConnection.getHeaderFields(); for (String headerKey : headers.keySet()) { if (!StringUtils.isEmpty(headerKey)) { response.setHeader(headerKey, StringUtils.join(headers.get(headerKey), ",")); }//from www .java2 s . c om } int responseCode = urlConnection.getResponseCode(); InputStream inputStream; if (responseCode >= 400) { inputStream = urlConnection.getErrorStream(); } else { inputStream = urlConnection.getInputStream(); } response.setStatus(responseCode); IOUtils.copy(inputStream, response.getOutputStream()); IOUtils.closeQuietly(inputStream); }
From source file:at.florian_lentsch.expirysync.net.JsonCaller.java
private void storeCookies(HttpURLConnection connection) { Map<String, List<String>> headerFields = connection.getHeaderFields(); if (headerFields == null) //for example happends when the server returns <forbidden> return;//from ww w. j a v a2s . c o m List<String> cookiesHeader = headerFields.get("Set-Cookie"); if (cookiesHeader != null) { for (String cookie : cookiesHeader) { this.cookieManager.getCookieStore().add(this.host, HttpCookie.parse(cookie).get(0)); } } }
From source file:at.florian_lentsch.expirysync.net.JsonCaller.java
private void determineTimeSkew(HttpURLConnection connection) { Map<String, List<String>> headerFields = connection.getHeaderFields(); if (headerFields == null) //for example happends when the server returns <forbidden> return;//from ww w . j a va2 s . c o m List<String> dateHeader = headerFields.get("Date"); if (dateHeader != null && dateHeader.size() > 0) { SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); Date date; try { date = format.parse(dateHeader.get(0)); } catch (ParseException e) { return; // ignore invalid http return header } JsonCaller.timeSkew = date.getTime() - System.currentTimeMillis(); } }
From source file:com.aperlambda.apercommon.connection.http.HttpRequestSender.java
private HttpResponse send(HttpURLConnection connection) throws IOException { connection.connect();/* w ww .ja v a 2 s . c o m*/ if (connection.getResponseCode() != 200) return new HttpResponse(connection.getResponseCode()); Map<String, String> headers = new HashMap<>(); connection.getHeaderFields().forEach((key, value) -> headers.put(key, value.get(0))); String body; InputStream iStream = null; try { iStream = connection.getInputStream(); String encoding = connection.getContentEncoding(); encoding = encoding == null ? "UTF-8" : encoding; body = IOUtils.toString(iStream, encoding); } finally { if (iStream != null) { iStream.close(); } } if (body == null) { throw new IOException("Unparseable response body! \n {" + body + "}"); } return new HttpResponse(connection.getResponseCode(), headers, body); }
From source file:io.apiman.manager.ui.server.servlets.UrlFetchProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*from www . j a v a2s . c o m*/ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = req.getHeader("X-Apiman-Url"); //$NON-NLS-1$ if (url == null) { resp.sendError(500, "No URL specified in X-Apiman-Url"); //$NON-NLS-1$ return; } URL remoteUrl = new URL(url); HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection(); InputStream remoteIS = null; OutputStream responseOS = null; try { 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); } 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:com.truebanana.http.HTTPResponse.java
protected static HTTPResponse from(HTTPRequest request, HttpURLConnection connection, InputStream content) { HTTPResponse response = new HTTPResponse(); response.originalRequest = request;//from ww w .ja va 2 s .c o m if (content != null) { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] data = new byte[16384]; int nRead; while ((nRead = content.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); response.content = buffer.toByteArray(); } catch (IOException e) { e.printStackTrace(); } } try { response.statusCode = connection.getResponseCode(); } catch (IOException e) { } String message = null; try { message = connection.getResponseMessage(); } catch (IOException e) { message = e.getLocalizedMessage(); } response.responseMessage = response.statusCode + (message != null ? " " + message : ""); response.headers = connection.getHeaderFields(); response.requestURL = connection.getURL().toString(); return response; }