List of usage examples for java.net HttpURLConnection getHeaderFields
public Map<String, List<String>> getHeaderFields()
From source file:org.inaetics.pubsub.demo.config.EtcdWrapper.java
/** * Delete an empty directory in etcd//from www.j av a 2 s. com * * @param key * @return * @throws MalformedURLException * @throws IOException */ public JsonNode deleteEmptyDirectory(String key) throws MalformedURLException, IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url + key + "?dir=true").openConnection(); connection.setRequestMethod("DELETE"); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); InputStream response = connection.getInputStream(); JsonNode result = new ObjectMapper().readTree(response); response.close(); AddEtcdIndex(result, Long.parseLong(connection.getHeaderFields().get("X-Etcd-Index").get(0))); return result; }
From source file:fr.xebia.servlet.filter.ExpiresFilterTest.java
protected void validate(HttpServlet servlet, Integer expectedMaxAgeInSeconds, int expectedResponseStatusCode) throws Exception { // SETUP/*from w w w .j ava 2s. c o m*/ int port = 6666; Server server = new Server(port); Context context = new Context(server, "/", Context.SESSIONS); MockFilterConfig filterConfig = new MockFilterConfig(); filterConfig.addInitParameter("ExpiresDefault", "access plus 1 minute"); filterConfig.addInitParameter("ExpiresByType text/xml; charset=utf-8", "access plus 3 minutes"); filterConfig.addInitParameter("ExpiresByType text/xml", "access plus 5 minutes"); filterConfig.addInitParameter("ExpiresByType text", "access plus 7 minutes"); filterConfig.addInitParameter("ExpiresExcludedResponseStatusCodes", "304, 503"); ExpiresFilter expiresFilter = new ExpiresFilter(); expiresFilter.init(filterConfig); context.addFilter(new FilterHolder(expiresFilter), "/*", Handler.REQUEST); context.addServlet(new ServletHolder(servlet), "/test"); server.start(); try { Calendar.getInstance(TimeZone.getTimeZone("GMT")); long timeBeforeInMillis = System.currentTimeMillis(); // TEST HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test") .openConnection(); // VALIDATE Assert.assertEquals(expectedResponseStatusCode, httpURLConnection.getResponseCode()); for (Entry<String, List<String>> field : httpURLConnection.getHeaderFields().entrySet()) { System.out.println(field.getKey() + ": " + StringUtils.arrayToDelimitedString(field.getValue().toArray(), ", ")); } Integer actualMaxAgeInSeconds; String cacheControlHeader = httpURLConnection.getHeaderField("Cache-Control"); if (cacheControlHeader == null) { actualMaxAgeInSeconds = null; } else { actualMaxAgeInSeconds = null; // System.out.println("Evaluate Cache-Control:" + // cacheControlHeader); StringTokenizer cacheControlTokenizer = new StringTokenizer(cacheControlHeader, ","); while (cacheControlTokenizer.hasMoreTokens() && actualMaxAgeInSeconds == null) { String cacheDirective = cacheControlTokenizer.nextToken(); // System.out.println("\tEvaluate directive: " + // cacheDirective); StringTokenizer cacheDirectiveTokenizer = new StringTokenizer(cacheDirective, "="); // System.out.println("countTokens=" + // cacheDirectiveTokenizer.countTokens()); if (cacheDirectiveTokenizer.countTokens() == 2) { String key = cacheDirectiveTokenizer.nextToken().trim(); String value = cacheDirectiveTokenizer.nextToken().trim(); if (key.equalsIgnoreCase("max-age")) { actualMaxAgeInSeconds = Integer.parseInt(value); } } } } if (expectedMaxAgeInSeconds == null) { Assert.assertNull("actualMaxAgeInSeconds '" + actualMaxAgeInSeconds + "' should be null", actualMaxAgeInSeconds); return; } Assert.assertNotNull(actualMaxAgeInSeconds); int deltaInSeconds = Math.abs(actualMaxAgeInSeconds - expectedMaxAgeInSeconds); Assert.assertTrue("actualMaxAgeInSeconds: " + actualMaxAgeInSeconds + ", expectedMaxAgeInSeconds: " + expectedMaxAgeInSeconds + ", request time: " + timeBeforeInMillis + " for content type " + httpURLConnection.getContentType(), deltaInSeconds < 2000); } finally { server.stop(); } }
From source file:org.bibsonomy.scraper.url.kde.blackwell.BlackwellSynergyScraper.java
/** FIXME: refactor * Gets the cookie which is needed to extract the content of aip pages. * (changed code from ScrapingContext.getContentAsString) * @param urlConn Connection to api page (from url.openConnection()) * @return The value of the cookie.//from w ww . j a v a 2 s . c o m * @throws IOException */ private String getCookie() throws IOException { HttpURLConnection urlConn = (HttpURLConnection) new URL("http://www.blackwell-synergy.com/help") .openConnection(); String cookie = null; urlConn.setAllowUserInteraction(true); urlConn.setDoInput(true); urlConn.setDoOutput(false); urlConn.setUseCaches(false); urlConn.setFollowRedirects(true); urlConn.setInstanceFollowRedirects(false); urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)"); urlConn.connect(); // extract cookie from header Map map = urlConn.getHeaderFields(); cookie = urlConn.getHeaderField("Set-Cookie"); if (cookie != null && cookie.indexOf(";") >= 0) cookie = cookie.substring(0, cookie.indexOf(";")); urlConn.disconnect(); return cookie; }
From source file:org.wso2.carbon.esb.passthru.transport.test.ESBJAVA4891ConsumeAndDiscardTest.java
private static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws AutomationFrameworkException, IOException { HttpURLConnection urlConnection = null; try {/*from w w w .ja va 2s .co m*/ urlConnection = (HttpURLConnection) endpoint.openConnection(); try { urlConnection.setRequestMethod("POST"); } catch (ProtocolException e) { throw new AutomationFrameworkException( "Shouldn't happen: HttpURLConnection doesn't support POST?? " + e.getMessage(), e); } urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); urlConnection.setAllowUserInteraction(false); urlConnection.setReadTimeout(10000); for (Map.Entry<String, String> e : headers.entrySet()) { urlConnection.setRequestProperty(e.getKey(), e.getValue()); } OutputStream out = urlConnection.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); writer.write(postBody); writer.close(); } catch (IOException e) { throw new AutomationFrameworkException("IOException while posting data " + e.getMessage(), e); } StringBuilder sb = new StringBuilder(); BufferedReader rd; try { rd = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator(); Map<String, String> responseHeaders = new HashMap<>(); String key; while (itr.hasNext()) { key = itr.next(); if (key != null) { responseHeaders.put(key, urlConnection.getHeaderField(key)); } } return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders); } catch (IOException e) { StringBuilder sb = new StringBuilder(); BufferedReader rd = null; rd = new BufferedReader( new InputStreamReader(urlConnection.getErrorStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } return new HttpResponse(sb.toString(), urlConnection.getResponseCode()); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:org.wso2.carbon.esb.passthru.transport.test.PartialInputStreamReadError.java
private static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws AutomationFrameworkException, IOException { HttpURLConnection urlConnection = null; try {//www . ja v a 2 s. c o m urlConnection = (HttpURLConnection) endpoint.openConnection(); try { urlConnection.setRequestMethod("POST"); } catch (ProtocolException e) { throw new AutomationFrameworkException( "Shouldn't happen: HttpURLConnection doesn't support POST?? " + e.getMessage(), e); } urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); urlConnection.setAllowUserInteraction(false); urlConnection.setReadTimeout(10000); for (Map.Entry<String, String> e : headers.entrySet()) { urlConnection.setRequestProperty(e.getKey(), e.getValue()); } OutputStream out = urlConnection.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); writer.write(postBody); writer.close(); } catch (IOException e) { throw new AutomationFrameworkException("IOException while posting data " + e.getMessage(), e); } StringBuilder sb = new StringBuilder(); BufferedReader rd; try { rd = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator(); Object responseHeaders = new HashMap(); String key; while (itr.hasNext()) { key = itr.next(); if (key != null) { ((Map) responseHeaders).put(key, urlConnection.getHeaderField(key)); } } return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), (Map) responseHeaders); } catch (IOException e) { StringBuilder sb = new StringBuilder(); BufferedReader rd = null; rd = new BufferedReader( new InputStreamReader(urlConnection.getErrorStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } return new HttpResponse(sb.toString(), urlConnection.getResponseCode()); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java
public static HttpResponse doDelete(URL endpoint, Map<String, String> headers) throws Exception { HttpURLConnection urlConnection = null; try {// w w w .jav a2 s .co m urlConnection = (HttpURLConnection) endpoint.openConnection(); try { urlConnection.setRequestMethod("DELETE"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support Delete??", e); } urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); urlConnection.setAllowUserInteraction(false); // setting headers if (headers != null && headers.size() > 0) { Iterator<String> itr = headers.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); urlConnection.setRequestProperty(key, headers.get(key)); } } // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } finally { if (rd != null) { rd.close(); } } Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator(); Map<String, String> responseHeaders = new HashMap(); while (itr.hasNext()) { String key = itr.next(); if (key != null) { responseHeaders.put(key, urlConnection.getHeaderField(key)); } } return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders); } catch (IOException e) { throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:com.jolira.testing.CachingRESTProxy.java
private void cacheResponse(final File queryDir, final HttpURLConnection connection, final InputStream in) throws IOException, FileNotFoundException { final String contentType = connection.getHeaderField(CONTENT_TYPE); final int code = connection.getResponseCode(); final String defaultContentType = getDefaultContentType(queryDir); final Map<String, List<String>> fields = connection.getHeaderFields(); final Collection<String> cookies = fields.get(SET_COOKIE); final boolean simple = code == SC_OK && equalsContentType(defaultContentType, contentType) && isEmpty(cookies); final File resourceFile = simple ? queryDir : getResourceFile(queryDir); copy(in, resourceFile);//from w ww.ja va 2 s. co m if (simple) { return; } final Properties prps = new Properties(); if (contentType != null) { prps.put(CONTENT_TYPE, contentType); } if (cookies != null) { int idx = 0; for (final String cookie : cookies) { final String key = getCookieKey(idx++); prps.put(key, cookie); } } prps.put(STATUS_PROPERTY, Integer.toString(code)); final File propertiesFile = getPropertiesFile(queryDir); final OutputStream out = new FileOutputStream(propertiesFile); try { prps.store(out, "gerated by " + CachingRESTProxy.class); } finally { out.close(); } }
From source file:org.apache.qpid.systest.rest.SaslRestTest.java
private int authenticateUser(HttpURLConnection requestChallengeConnection, String userName, String userPassword, String mechanism) throws IOException, JsonParseException, JsonMappingException, Exception { // get the response Map<String, Object> response = getRestTestHelper().readJsonResponseAsMap(requestChallengeConnection); String challenge = (String) response.get("challenge"); assertNotNull("Challenge is not found", challenge); // preserve cookies to have the same server session List<String> cookies = requestChallengeConnection.getHeaderFields().get("Set-Cookie"); // generate the authentication response for the challenge received byte[] challengeBytes = Base64.decodeBase64(challenge); byte[] responseBytes = generateClientResponse(mechanism, userName, userPassword, challengeBytes); String responseData = Base64.encodeBase64String(responseBytes); String requestParameters = ("id=" + response.get("id") + "&response=" + responseData); // re-open connection HttpURLConnection authenticateConnection = getRestTestHelper().openManagementConnection("/rest/sasl", "POST"); // set cookies to use the same server session applyCookiesToConnection(cookies, authenticateConnection); OutputStream os = authenticateConnection.getOutputStream(); os.write(requestParameters.getBytes()); os.flush();/*from w w w .j a va 2 s .c om*/ return authenticateConnection.getResponseCode(); }
From source file:fr.seeks.SuggestionProvider.java
public void setCursorOfQueryThrow(Uri uri, String query, MatrixCursor matrix) throws MalformedURLException, IOException { String url = getUrlFromKeywords(query); Log.v(TAG, "Query:" + url); String json = null;/*from w w w. j a v a 2 s.co m*/ while (json == null) { HttpURLConnection connection = null; connection = (HttpURLConnection) (new URL(url)).openConnection(); try { connection.setDoOutput(true); connection.setChunkedStreamingMode(0); connection.setInstanceFollowRedirects(true); connection.connect(); int response = connection.getResponseCode(); if (response == HttpURLConnection.HTTP_MOVED_PERM || response == HttpURLConnection.HTTP_MOVED_TEMP) { Map<String, List<String>> list = connection.getHeaderFields(); for (Entry<String, List<String>> entry : list.entrySet()) { String value = ""; for (String s : entry.getValue()) { value = value + ";" + s; } Log.v(TAG, entry.getKey() + ":" + value); } // FIXME url = ""; return; } InputStream in = connection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(in)); StringBuilder builder = new StringBuilder(); String line; while ((line = r.readLine()) != null) { builder.append(line); } json = builder.toString(); /* * Log.v(TAG, "** JSON START **"); Log.v(TAG, json); Log.v(TAG, * "** JSON END **"); */ } catch (IOException e) { e.printStackTrace(); return; } finally { connection.disconnect(); } } JSONArray snippets; JSONObject object; JSONArray suggestions; Boolean show_snippets = mPrefs.getBoolean("show_snippets", false); if (show_snippets) { try { object = (JSONObject) new JSONTokener(json).nextValue(); snippets = object.getJSONArray("snippets"); } catch (JSONException e) { e.printStackTrace(); return; } Log.v(TAG, "Snippets found: " + snippets.length()); for (int i = 0; i < snippets.length(); i++) { JSONObject snip; try { snip = snippets.getJSONObject(i); matrix.newRow().add(i).add(snip.getString("title")).add(snip.getString("summary")) .add(snip.getString("title")).add(Intent.ACTION_SEND).add(snip.getString("url")); } catch (JSONException e) { e.printStackTrace(); continue; } } } else { try { object = (JSONObject) new JSONTokener(json).nextValue(); suggestions = object.getJSONArray("suggestions"); } catch (JSONException e) { e.printStackTrace(); return; } Log.v(TAG, "Suggestions found: " + suggestions.length()); for (int i = 0; i < suggestions.length(); i++) { try { matrix.newRow().add(i).add(suggestions.getString(i)).add("").add(suggestions.getString(i)) .add(Intent.ACTION_SEARCH).add(""); } catch (JSONException e) { e.printStackTrace(); continue; } } } getContext().getContentResolver().notifyChange(uri, null); }
From source file:com.adyen.httpclient.HttpURLConnectionClient.java
/** * Does a POST request with raw body/*from w w w . j a va 2 s .co m*/ */ private String doPostRequest(HttpURLConnection httpConnection, String requestBody) throws IOException, HTTPClientException { String response = null; OutputStream outputStream = httpConnection.getOutputStream(); outputStream.write(requestBody.getBytes()); outputStream.flush(); int responseCode = httpConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { //Read the response from the error stream if (httpConnection.getErrorStream() != null) { response = getResponseBody(httpConnection.getErrorStream()); } HTTPClientException httpClientException = new HTTPClientException(responseCode, "HTTP Exception", httpConnection.getHeaderFields(), response); throw httpClientException; } //InputStream is only available on successful requests >= 200 <400 response = getResponseBody(httpConnection.getInputStream()); // close the connection httpConnection.disconnect(); return response; }