List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:io.ericwittmann.corsproxy.ProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from ww w. j a va2 s. co m @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = "https://issues.jboss.org" + req.getPathInfo(); if (req.getQueryString() != null) { url += "?" + req.getQueryString(); } System.out.println("Proxying to: " + url); boolean isWrite = req.getMethod().equalsIgnoreCase("post") || req.getMethod().equalsIgnoreCase("put"); URL remoteUrl = new URL(url); HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection(); if (isWrite) { remoteConn.setDoOutput(true); } String auth = req.getHeader("Authorization"); if (auth != null) { remoteConn.setRequestProperty("Authorization", auth); } if (isWrite) { InputStream requestIS = null; OutputStream remoteOS = null; try { requestIS = req.getInputStream(); remoteOS = remoteConn.getOutputStream(); IOUtils.copy(requestIS, remoteOS); remoteOS.flush(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); return; } finally { IOUtils.closeQuietly(requestIS); IOUtils.closeQuietly(remoteOS); } } InputStream remoteIS = null; OutputStream responseOS = null; try { 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-2$ remoteIS = remoteConn.getInputStream(); responseOS = resp.getOutputStream(); IOUtils.copy(remoteIS, responseOS); resp.flushBuffer(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); } finally { IOUtils.closeQuietly(responseOS); IOUtils.closeQuietly(remoteIS); } }
From source file:org.spigotmc.timings.TimingsExport.java
@Override public void run() { sender.sendMessage(ChatColor.GREEN + "Preparing Timings Report..."); out.put("data", toObjectMapper(history, new Function<TimingHistory, JSONPair>() { @Override/*from w ww. j av a2 s . c o m*/ public JSONPair apply(TimingHistory input) { return input.export(); } })); String response = null; try { HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection(); con.setDoOutput(true); con.setRequestProperty("User-Agent", "Spigot/" + Bukkit.getServerName() + "/" + InetAddress.getLocalHost().getHostName()); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); OutputStream request = new GZIPOutputStream(con.getOutputStream()) { { this.def.setLevel(7); } }; request.write(JSONValue.toJSONString(out).getBytes("UTF-8")); request.close(); response = getResponse(con); if (con.getResponseCode() != 302) { sender.sendMessage( ChatColor.RED + "Upload Error: " + con.getResponseCode() + ": " + con.getResponseMessage()); sender.sendMessage(ChatColor.RED + "Check your logs for more information"); if (response != null) { Bukkit.getLogger().log(Level.SEVERE, response); } return; } String location = con.getHeaderField("Location"); sender.sendMessage(ChatColor.GREEN + "View Timings Report: " + location); if (!(sender instanceof ConsoleCommandSender)) { Bukkit.getLogger().log(Level.INFO, "View Timings Report: " + location); } if (response != null && !response.isEmpty()) { Bukkit.getLogger().log(Level.INFO, "Timing Response: " + response); } } catch (IOException ex) { sender.sendMessage(ChatColor.RED + "Error uploading timings, check your logs for more information"); if (response != null) { Bukkit.getLogger().log(Level.SEVERE, response); } Bukkit.getLogger().log(Level.SEVERE, "Could not paste timings", ex); } }
From source file:com.cloudant.http.interceptors.Replay429Interceptor.java
@Override public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { // Get or init the stored context for this interceptor try {//from w ww.j a va 2 s . com HttpURLConnection urlConnection = context.connection.getConnection(); int code = urlConnection.getResponseCode(); // We only want to take action on a 429 response if (code != 429) { return context; } // We received a 429 // Get the counter from the request context state AtomicInteger attemptCounter = context.getState(this, ATTEMPT, AtomicInteger.class); // If there was no counter yet, then this is the first 429 received for this request if (attemptCounter == null) { context.setState(this, ATTEMPT, (attemptCounter = new AtomicInteger())); } // Get the current value, and then increment for the next time round int attempt = attemptCounter.getAndIncrement(); // Check if we have remaining replays if (attempt < numberOfReplays && context.connection.getNumberOfRetriesRemaining() > 0) { // Calculate the backoff time, 2^n * initial sleep long sleepTime = initialSleep * Math.round(Math.pow(2, attempt)); // If the response includes a Retry-After then that is when we will retry, otherwise // we use the doubling sleep String retryAfter = preferRetryAfter ? urlConnection.getHeaderField("Retry-After") : null; if (retryAfter != null) { // See https://tools.ietf.org/html/rfc6585#section-4 // Whilst not specified for 429 for 3xx or 503 responses the Retry-After header // is expressed as an integer number of seconds or a date in one of the 3 HTTP // date formats https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 // Cloudant servers should give us an integer number of seconds, so don't worry // about parsing dates for now. try { sleepTime = Long.parseLong(retryAfter) * 1000; if (sleepTime > RETRY_AFTER_CAP) { sleepTime = RETRY_AFTER_CAP; logger.severe("Server specified Retry-After value in excess of one " + "hour, capping retry."); } } catch (NumberFormatException nfe) { logger.warning( "Invalid Retry-After value from server falling back to " + "default backoff."); } } // Read the reasons and log a warning InputStream errorStream = urlConnection.getErrorStream(); try { String errorString = IOUtils.toString(errorStream, "UTF-8"); logger.warning(errorString + " will retry in " + sleepTime + " ms"); } finally { errorStream.close(); } logger.fine("Too many requests backing off for " + sleepTime + " ms."); // Sleep the thread for the appropriate backoff time try { TimeUnit.MILLISECONDS.sleep(sleepTime); } catch (InterruptedException e) { logger.fine("Interrupted during 429 backoff wait."); // If the thread was interrupted we'll just continue and try again a bit earlier // than planned. } // Get ready to replay the request after the backoff time context.replayRequest = true; return context; } else { return context; } } catch (IOException e) { throw new HttpConnectionInterceptorException(e); } }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testSetAndGetFromSession() throws Exception { long value = System.currentTimeMillis(); // Request to first operation HttpURLConnection urlConn = request("/test/v1/set-session/" + value, HttpMethod.GET); assertEquals(204, urlConn.getResponseCode()); String setCookieHeader = urlConn.getHeaderField("Set-Cookie"); assertNotNull(setCookieHeader);/* ww w.j av a 2 s. co m*/ urlConn.disconnect(); // Request to 2nd operation urlConn = request("/test/v1/get-session/", HttpMethod.GET); urlConn.setRequestProperty("Cookie", setCookieHeader); assertEquals(200, urlConn.getResponseCode()); setCookieHeader = urlConn.getHeaderField("Set-Cookie"); assertNull(setCookieHeader); String content = getContent(urlConn); // content retrieved & returned from session assertEquals(String.valueOf(value), content); urlConn.disconnect(); }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testSetAndGetFromSession2() throws Exception { long value = System.currentTimeMillis(); // Request to first operation HttpURLConnection urlConn = request("/test/v1/set-session2/" + value, HttpMethod.GET); assertEquals(200, urlConn.getResponseCode()); String setCookieHeader = urlConn.getHeaderField("Set-Cookie"); assertNotNull(setCookieHeader);//from w w w . java2 s .c om String content = getContent(urlConn); assertEquals(String.valueOf(value), content); urlConn.disconnect(); // Request to 2nd operation urlConn = request("/test/v1/get-session/", HttpMethod.GET); urlConn.setRequestProperty("Cookie", setCookieHeader); assertEquals(200, urlConn.getResponseCode()); setCookieHeader = urlConn.getHeaderField("Set-Cookie"); assertNull(setCookieHeader); content = getContent(urlConn); // content retrieved & returned from session assertEquals(String.valueOf(value), content); urlConn.disconnect(); }
From source file:org.jared.synodroid.ds.server.SimpleSynoServer.java
/** * Send a request to the server./*ww w .j a va 2 s .c o m*/ * * @param uriP * The part of the URI ie: /webman/doit.cgi * @param requestP * The query in the form 'param1=foo¶m2=yes' * @param methodP * The method to send this request * @return A JSONObject containing the response of the server * @throws DSMException */ public JSONObject sendJSONRequest(String uriP, String requestP, String methodP, boolean log, int MAX_RETRY) throws Exception { HttpURLConnection con = null; OutputStreamWriter wr = null; BufferedReader br = null; StringBuffer sb = null; Exception last_exception = null; try { // For some reason in Gingerbread I often get a response code of -1. // Here I retry for a maximum of MAX_RETRY to send the request and it usually succeed at the second try... int retry = 0; while (retry <= MAX_RETRY) { try { // Create the connection con = createConnection(uriP, requestP, methodP, log); // Add the parameters wr = new OutputStreamWriter(con.getOutputStream()); wr.write(requestP); // Send the request wr.flush(); wr.close(); // Try to retrieve the session cookie String newCookie = con.getHeaderField("set-cookie"); if (newCookie != null) { synchronized (this) { setCookie(newCookie); } if (DEBUG) Log.v(Synodroid.DS_TAG, "Retreived cookies: " + cookies); } // Now read the reponse and build a string with it br = new BufferedReader(new InputStreamReader(con.getInputStream())); sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); // Verify is response if not -1, otherwise take reason from the header if (con.getResponseCode() == -1) { retry++; last_exception = null; if (DEBUG) Log.w(Synodroid.DS_TAG, "Response code is -1 (retry: " + retry + ")"); } else { if (DEBUG) Log.d(Synodroid.DS_TAG, "Response is: " + sb.toString()); JSONObject respJSO = null; try { respJSO = new JSONObject(sb.toString()); } catch (JSONException je) { respJSO = new JSONObject(); } return respJSO; } } catch (EOFException e) { if (DEBUG) Log.w(Synodroid.DS_TAG, "Caught EOFException while contacting the server, retying..."); retry++; last_exception = e; } catch (SocketException e) { if (DEBUG) Log.e(Synodroid.DS_TAG, "Caught SocketException while contacting the server, stopping..."); throw e; } catch (SSLHandshakeException e) { if (DEBUG) Log.e(Synodroid.DS_TAG, "Caught SSLHandshakeException while contacting the server, stopping..."); throw e; } catch (FileNotFoundException e) { String msg = e.getMessage(); if (DEBUG) Log.e(Synodroid.DS_TAG, "Could not find file " + msg + "\nProbably wrong DSM version, stopping..."); throw e; } catch (Exception e) { if (DEBUG) Log.e(Synodroid.DS_TAG, "Caught exception while contacting the server, retying...", e); retry++; last_exception = e; } finally { con.disconnect(); } } if (last_exception != null) throw last_exception; throw new GenericException(); } // Finally close everything finally { wr = null; br = null; sb = null; con = null; } }
From source file:com.portfolio.data.attachment.FileServlet.java
void InitAnswer(HttpURLConnection connection, HttpServletResponse response, String referer) throws MalformedURLException, IOException { String ref = null;/*from w ww . j a v a 2 s .c om*/ if (referer != null) { int first = referer.indexOf('/', 7); int last = referer.lastIndexOf('/'); ref = referer.substring(first, last); } response.setContentType(connection.getContentType()); response.setStatus(connection.getResponseCode()); response.setContentLength(connection.getContentLength()); /// Transfer headers Map<String, List<String>> headers = connection.getHeaderFields(); int size = headers.size(); for (int i = 1; i < size; ++i) { String key = connection.getHeaderFieldKey(i); String value = connection.getHeaderField(i); // response.setHeader(key, value); response.addHeader(key, value); } /// Deal with correct path with set cookie List<String> setValues = headers.get("Set-Cookie"); if (setValues != null) { String setVal = setValues.get(0); int pathPlace = setVal.indexOf("Path="); if (pathPlace > 0) { setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break setVal = setVal + ref; response.setHeader("Set-Cookie", setVal); } } }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testGzipCompressionWithNoGzipAccept() throws Exception { HttpURLConnection urlConn = request("/test/v1/gzipfile", HttpMethod.GET); assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode()); String contentEncoding = urlConn.getHeaderField(HttpHeaders.CONTENT_ENCODING); assertTrue(contentEncoding == null || !contentEncoding.contains("gzip")); InputStream downStream = urlConn.getInputStream(); assertTrue(IOUtils.toByteArray(downStream).length == IOUtils.toByteArray( Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").openStream()).length); }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testDownloadPngFile() throws Exception { HttpURLConnection urlConn = request("/test/v1/fileserver/png", HttpMethod.GET); assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode()); String contentType = urlConn.getHeaderField(HttpHeaders.CONTENT_TYPE); assertTrue("image/png".equalsIgnoreCase(contentType)); InputStream downStream = urlConn.getInputStream(); File file = new File(Thread.currentThread().getContextClassLoader().getResource("testPngFile.png").toURI()); assertTrue(isStreamEqual(downStream, new FileInputStream(file))); }