List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:net.andylizi.colormotd.Updater.java
private boolean checkUpdate() { if (file != null && file.exists()) { cancel();/*from w w w .j a v a 2 s . c o m*/ } URL url; try { url = new URL(UPDATE_URL); } catch (MalformedURLException ex) { if (DEBUG) { ex.printStackTrace(); } return false; } try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.addRequestProperty("User-Agent", userAgent); if (etag != null) { conn.addRequestProperty("If-None-Match", etag); } conn.addRequestProperty("Accept", "application/json,text/plain,*/*;charset=utf-8"); conn.addRequestProperty("Accept-Encoding", "gzip"); conn.addRequestProperty("Cache-Control", "no-cache"); conn.addRequestProperty("Date", new Date().toString()); conn.addRequestProperty("Connection", "close"); conn.setDoInput(true); conn.setDoOutput(false); conn.setConnectTimeout(2000); conn.setReadTimeout(2000); conn.connect(); if (conn.getHeaderField("ETag") != null) { etag = conn.getHeaderField("ETag"); } if (DEBUG) { logger.log(Level.INFO, "DEBUG ResponseCode: {0}", conn.getResponseCode()); logger.log(Level.INFO, "DEBUG ETag: {0}", etag); } if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return false; } else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { return false; } BufferedReader input = null; if (conn.getContentEncoding() != null && conn.getContentEncoding().contains("gzip")) { input = new BufferedReader( new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"), 1); } else { input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 1); } StringBuilder builder = new StringBuilder(); String buffer = null; while ((buffer = input.readLine()) != null) { builder.append(buffer); } try { JSONObject jsonObj = (JSONObject) new JSONParser().parse(builder.toString()); int build = ((Number) jsonObj.get("build")).intValue(); if (build <= ColorMOTD.buildVersion) { return false; } String version = (String) jsonObj.get("version"); String msg = (String) jsonObj.get("msg"); String download_url = (String) jsonObj.get("url"); newVersion = new NewVersion(version, build, msg, download_url); return true; } catch (ParseException ex) { if (DEBUG) { ex.printStackTrace(); } exception = ex; return false; } } catch (SocketTimeoutException ex) { return false; } catch (IOException ex) { if (DEBUG) { ex.printStackTrace(); } exception = ex; return false; } }
From source file:eionet.cr.harvest.PullHarvest.java
/** * * @param connection// ww w . ja va 2s.com * @return * @throws MalformedURLException */ private String getRedirectUrl(HttpURLConnection connection) throws MalformedURLException { String location = connection.getHeaderField("Location"); if (location != null) { try { // If location does not seem to be an absolute URI, consider it relative to the // URL of this URL connection. if (!(new URI(location).isAbsolute())) { location = new URL(connection.getURL(), location).toString(); } } catch (URISyntaxException e) { // Ignoring on purpose. } // we want to avoid fragment parts in CR harvest source URLs location = StringUtils.substringBefore(location, "#"); } return location; }
From source file:org.cytoscape.app.internal.net.server.CyHttpdImplTest.java
@Test public void testHttpd() throws Exception { final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2608)); final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl(); httpd.addResponder(new CyHttpResponder() { public Pattern getURIPattern() { return Pattern.compile("^/testA$"); }//from www . jav a 2 s .com public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) { return responseFactory.createHttpResponse(HttpStatus.SC_OK, "testA response ok", "text/html"); } }); httpd.addResponder(new CyHttpResponder() { public Pattern getURIPattern() { return Pattern.compile("^/testB$"); } public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) { return responseFactory.createHttpResponse(HttpStatus.SC_OK, "testB response ok", "text/html"); } }); httpd.addBeforeResponse(new CyHttpBeforeResponse() { public CyHttpResponse intercept(CyHttpRequest request) { if (request.getMethod().equals("OPTIONS")) return responseFactory.createHttpResponse(HttpStatus.SC_OK, "options intercepted", "text/html"); else return null; } }); httpd.addAfterResponse(new CyHttpAfterResponse() { public CyHttpResponse intercept(CyHttpRequest request, CyHttpResponse response) { response.getHeaders().put("SomeRandomHeader", "WowInterceptWorks"); return response; } }); assertFalse(httpd.isRunning()); httpd.start(); assertTrue(httpd.isRunning()); final String url = "http://localhost:2608/"; // test if normal response works HttpURLConnection connection = connectToURL(url + "testA", "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(readConnection(connection), "testA response ok"); connection = connectToURL(url + "testB", "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(readConnection(connection), "testB response ok"); // test if 404 response works connection = connectToURL(url + "testX", "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND); // test if before intercept works connection = connectToURL(url + "testA", "OPTIONS"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(readConnection(connection), "options intercepted"); // test if after intercept works connection = connectToURL(url + "testA", "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(connection.getHeaderField("SomeRandomHeader"), "WowInterceptWorks"); httpd.stop(); assertFalse(httpd.isRunning()); }
From source file:mobac.mapsources.loader.MapPackManager.java
public String downloadMD5SumList() throws IOException, UpdateFailedException { String md5eTag = Settings.getInstance().mapSourcesUpdate.etag; log.debug("Last md5 eTag: " + md5eTag); String updateUrl = System.getProperty("mobac.updateurl"); if (updateUrl == null) throw new RuntimeException("Update url not present"); byte[] data = null; // Proxy p = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved("localhost", 8888)); HttpURLConnection conn = (HttpURLConnection) new URL(updateUrl).openConnection(); conn.setInstanceFollowRedirects(false); if (md5eTag != null) conn.addRequestProperty("If-None-Match", md5eTag); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { log.debug("No newer md5 file available"); return null; }/*from w w w . j av a 2 s .c om*/ if (responseCode != HttpURLConnection.HTTP_OK) throw new UpdateFailedException( "Invalid HTTP response: " + responseCode + " for update url " + conn.getURL()); // Case HTTP_OK InputStream in = conn.getInputStream(); data = Utilities.getInputBytes(in); in.close(); Settings.getInstance().mapSourcesUpdate.etag = conn.getHeaderField("ETag"); log.debug("New md5 file retrieved"); String md5sumList = new String(data); return md5sumList; }
From source file:net.andylizi.colormotd.anim.updater.Updater.java
private boolean checkUpdate() { if (new File(Bukkit.getUpdateFolderFile(), fileName).exists()) { cancel();/* w w w . ja v a2 s. c om*/ } URL url; try { url = new URL(UPDATE_URL); } catch (MalformedURLException ex) { if (DEBUG) { ex.printStackTrace(); } return false; } try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.addRequestProperty("User-Agent", USER_AGENT); if (etag != null) { conn.addRequestProperty("If-None-Match", etag); } conn.addRequestProperty("Accept", "application/json,text/plain,*/*;charset=utf-8"); conn.addRequestProperty("Accept-Encoding", "gzip"); conn.addRequestProperty("Cache-Control", "no-cache"); conn.addRequestProperty("Date", new Date().toString()); conn.addRequestProperty("Connection", "close"); conn.setDoInput(true); conn.setDoOutput(false); conn.setConnectTimeout(2000); conn.setReadTimeout(2000); conn.connect(); if (conn.getHeaderField("ETag") != null) { etag = conn.getHeaderField("ETag"); } if (DEBUG) { logger.log(Level.INFO, "DEBUG ResponseCode: {0}", conn.getResponseCode()); logger.log(Level.INFO, "DEBUG ETag: {0}", etag); } if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return false; } else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { return false; } BufferedReader input = null; if (conn.getContentEncoding() != null && conn.getContentEncoding().contains("gzip")) { input = new BufferedReader( new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"), 1); } else { input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 1); } StringBuilder builder = new StringBuilder(); String buffer = null; while ((buffer = input.readLine()) != null) { builder.append(buffer); } try { JSONObject jsonObj = (JSONObject) new JSONParser().parse(builder.toString()); int build = ((Number) jsonObj.get("build")).intValue(); if (build <= buildVersion) { return false; } String version = (String) jsonObj.get("version"); String msg = (String) jsonObj.get("msg"); String download_url = (String) jsonObj.get("url"); newVersion = new NewVersion(version, build, msg, download_url); return true; } catch (ParseException ex) { if (DEBUG) { ex.printStackTrace(); } exception = ex; return false; } } catch (SocketTimeoutException ex) { return false; } catch (IOException ex) { if (DEBUG) { ex.printStackTrace(); } exception = ex; return false; } }
From source file:osmcd.mapsources.loader.MapPackManager.java
public String downloadMD5SumList() throws IOException, UpdateFailedException { String md5eTag = Settings.getInstance().mapSourcesUpdate.etag; log.debug("Last md5 eTag: " + md5eTag); String updateUrl = System.getProperty("osmcd.updateurl"); if (updateUrl == null) throw new RuntimeException("Update url not present"); byte[] data = null; // Proxy p = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved("localhost", 8888)); HttpURLConnection conn = (HttpURLConnection) new URL(updateUrl).openConnection(); conn.setInstanceFollowRedirects(false); if (md5eTag != null) conn.addRequestProperty("If-None-Match", md5eTag); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { log.debug("No newer md5 file available"); return null; }/*from ww w.j a v a 2 s . c om*/ if (responseCode != HttpURLConnection.HTTP_OK) throw new UpdateFailedException( "Invalid HTTP response: " + responseCode + " for update url " + conn.getURL()); // Case HTTP_OK InputStream in = conn.getInputStream(); data = Utilities.getInputBytes(in); in.close(); Settings.getInstance().mapSourcesUpdate.etag = conn.getHeaderField("ETag"); log.debug("New md5 file retrieved"); String md5sumList = new String(data); return md5sumList; }
From source file:org.apache.taverna.activities.interaction.InteractionActivityRunnable.java
private void postInteractionMessage(final String id, final Entry entry, final String interactionUrlString, final String runId) throws IOException { entry.addLink(StringEscapeUtils.escapeXml(interactionUrlString), "presentation"); entry.setContentAsXhtml("<p><a href=\"" + StringEscapeUtils.escapeXml(interactionUrlString) + "\">Open: " + StringEscapeUtils.escapeXml(interactionUrlString) + "</a></p>"); URL feedUrl;//from w w w. j av a2s . co m feedUrl = new URL(interactionPreference.getFeedUrlString()); final String entryContent = ((FOMElement) entry).toFormattedString(); final HttpURLConnection httpCon = (HttpURLConnection) feedUrl.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestProperty("Content-Type", "application/atom+xml;type=entry;charset=UTF-8"); httpCon.setRequestProperty("Content-Length", "" + entryContent.length()); httpCon.setRequestProperty("Slug", id); httpCon.setRequestMethod("POST"); httpCon.setConnectTimeout(5000); final OutputStream outputStream = httpCon.getOutputStream(); IOUtils.write(entryContent, outputStream, "UTF-8"); outputStream.close(); final int response = httpCon.getResponseCode(); if ((response < 0) || (response >= 400)) { logger.error("Received response code" + response); throw (new IOException("Received response code " + response)); } if (response == HttpURLConnection.HTTP_CREATED) { interactionRecorder.addResource(runId, id, httpCon.getHeaderField("Location")); } }
From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java
private String getIconUrlWithHttpRedirect(String imageUrl) throws IOException { URL url = new URL(imageUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); int statusCode = conn.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_SEE_OTHER) { return conn.getHeaderField("Location"); } else {/*from w ww .j a v a2 s .co m*/ return imageUrl; } }
From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java
/** * Send form post/*from w w w . j ava 2s .co m*/ * * @param form * @param forms * @return * @throws MalformedURLException * @throws IOException */ public static Form sendPostForm(Form form, Form[] forms) throws MalformedURLException, IOException { URL obj = new URL(form.getUrl().trim()); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setDoInput(true); if (forms != null) { con.setDoOutput(true); // optional default is GET con.setRequestMethod("POST"); } //add request header con.setRequestProperty("User-Agent", DefaultConfig.USER_AGENT); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setRequestProperty("Referer", form.getReferer()); con.setRequestProperty("Origin", form.getOrigin()); con.setRequestProperty("Host", form.getHost()); if (COOKIE != null) { try { con.setRequestProperty("Cookie", COOKIE); } catch (Exception ex) { DCXLogger.error(Utils.class, Level.SEVERE, ex); } } String urlParameters = ""; if (forms != null) { for (Form fb : forms) { urlParameters += "&" + fb.getKey() + "=" + fb.getValue(); } urlParameters = urlParameters.substring(1); try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) { wr.writeBytes(urlParameters); wr.close(); } } if (con.getHeaderField("Set-Cookie") != null) { COOKIE = con.getHeaderField("Set-Cookie"); } Form form1 = new Form(); form1.setResponseCode(con.getResponseCode()); StringBuilder response = new StringBuilder(); if (form1.getResponseCode() == 200) { try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } form1.setResult(response.toString()); } return form1; }
From source file:org.apache.hadoop.security.token.delegation.web.TestWebDelegationToken.java
private void testDelegationTokenAuthenticatorCalls(final boolean useQS) throws Exception { final Server jetty = createJettyServer(); Context context = new Context(); context.setContextPath("/foo"); jetty.setHandler(context);/* w w w . j av a2 s. c o m*/ context.addFilter(new FilterHolder(AFilter.class), "/*", 0); context.addServlet(new ServletHolder(PingServlet.class), "/bar"); try { jetty.start(); final URL nonAuthURL = new URL(getJettyURL() + "/foo/bar"); URL authURL = new URL(getJettyURL() + "/foo/bar?authenticated=foo"); URL authURL2 = new URL(getJettyURL() + "/foo/bar?authenticated=bar"); DelegationTokenAuthenticatedURL.Token token = new DelegationTokenAuthenticatedURL.Token(); final DelegationTokenAuthenticatedURL aUrl = new DelegationTokenAuthenticatedURL(); aUrl.setUseQueryStringForDelegationToken(useQS); try { aUrl.getDelegationToken(nonAuthURL, token, FOO_USER); Assert.fail(); } catch (Exception ex) { Assert.assertTrue(ex.getMessage().contains("401")); } aUrl.getDelegationToken(authURL, token, FOO_USER); Assert.assertNotNull(token.getDelegationToken()); Assert.assertEquals(new Text("token-kind"), token.getDelegationToken().getKind()); aUrl.renewDelegationToken(authURL, token); try { aUrl.renewDelegationToken(nonAuthURL, token); Assert.fail(); } catch (Exception ex) { Assert.assertTrue(ex.getMessage().contains("401")); } aUrl.getDelegationToken(authURL, token, FOO_USER); try { aUrl.renewDelegationToken(authURL2, token); Assert.fail(); } catch (Exception ex) { Assert.assertTrue(ex.getMessage().contains("403")); } aUrl.getDelegationToken(authURL, token, FOO_USER); aUrl.cancelDelegationToken(authURL, token); aUrl.getDelegationToken(authURL, token, FOO_USER); aUrl.cancelDelegationToken(nonAuthURL, token); aUrl.getDelegationToken(authURL, token, FOO_USER); try { aUrl.renewDelegationToken(nonAuthURL, token); } catch (Exception ex) { Assert.assertTrue(ex.getMessage().contains("401")); } aUrl.getDelegationToken(authURL, token, "foo"); UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); ugi.addToken(token.getDelegationToken()); ugi.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { HttpURLConnection conn = aUrl.openConnection(nonAuthURL, new DelegationTokenAuthenticatedURL.Token()); Assert.assertEquals(HttpServletResponse.SC_OK, conn.getResponseCode()); if (useQS) { Assert.assertNull(conn.getHeaderField("UsingHeader")); Assert.assertNotNull(conn.getHeaderField("UsingQueryString")); } else { Assert.assertNotNull(conn.getHeaderField("UsingHeader")); Assert.assertNull(conn.getHeaderField("UsingQueryString")); } return null; } }); } finally { jetty.stop(); } }