List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:fr.xebia.servlet.filter.ExpiresFilterTest.java
protected void validate(HttpServlet servlet, Integer expectedMaxAgeInSeconds, int expectedResponseStatusCode) throws Exception { // SETUP//from w ww. j a va 2 s . 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:com.ontotext.s4.client.HttpClient.java
/** * Perform an HTTP GET request on a URL whose response is expected to * be a 3xx redirection, and return the target redirection URL. * * @param source the URL to request (relative URLs will resolve against the {@link #getBaseUrl() base URL}). * @return the URL returned by the "Location" header of the redirection response. * @throws HttpClientException if an exception occurs during * processing, or the server returns a 4xx or 5xx error * response (in which case the response JSON message will be * available as a {@link JsonNode} in the exception), or if * the response was not a 3xx redirection. *//* ww w. j a va 2 s . c o m*/ public URL getRedirect(URL source) throws HttpClientException { try { HttpURLConnection connection = (HttpURLConnection) source.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", authorizationHeader); connection.setRequestProperty("Accept", "application/json"); connection.setInstanceFollowRedirects(false); int responseCode = connection.getResponseCode(); // make sure we read any response content readResponseOrError(connection, new TypeReference<JsonNode>() { }, false); if (responseCode >= 300 && responseCode < 400) { // it was a redirect String redirectUrl = connection.getHeaderField("Location"); return new URL(redirectUrl); } else { throw new HttpClientException("Expected redirect but got " + responseCode); } } catch (IOException e) { throw new HttpClientException(e); } }
From source file:com.portfolio.data.attachment.FileServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { initialize(request);/*from www. j a va 2 s . c om*/ int userId = 0; int groupId = 0; String user = ""; String context = request.getContextPath(); String url = request.getPathInfo(); HttpSession session = request.getSession(true); if (session != null) { Integer val = (Integer) session.getAttribute("uid"); if (val != null) userId = val; val = (Integer) session.getAttribute("gid"); if (val != null) groupId = val; user = (String) session.getAttribute("user"); } Credential credential = null; try { //On initialise le dataProvider Connection c = null; if (ds == null) // Case where we can't deploy context.xml { c = getConnection(); } else { c = ds.getConnection(); } dataProvider.setConnection(c); credential = new Credential(c); } catch (Exception e) { e.printStackTrace(); } // ===================================================================================== boolean trace = false; StringBuffer outTrace = new StringBuffer(); StringBuffer outPrint = new StringBuffer(); String logFName = null; response.setCharacterEncoding("UTF-8"); System.out.println("FileServlet::doGet"); try { // ====== URI : /resources/file[/{lang}]/{context-id} // ====== PathInfo: /resources/file[/{uuid}?lang={fr|en}&size={S|L}] pathInfo // String uri = request.getRequestURI(); String[] token = url.split("/"); String uuid = token[1]; //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile:"+request.getRemoteAddr()+":"+uri); /// FIXME: Passe la scurit si la source provient de localhost, il faudrait un change afin de s'assurer que n'importe quel servlet ne puisse y accder String sourceip = request.getRemoteAddr(); System.out.println("IP: " + sourceip); /// Vrification des droits d'accs // TODO: Might be something special with proxy and export/PDF, to investigate if (!ourIPs.contains(sourceip)) { if (userId == 0) throw new RestWebApplicationException(Status.FORBIDDEN, ""); if (!credential.hasNodeRight(userId, groupId, uuid, Credential.READ)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit READ sur le noeud "+nodeUuid); } } else // Si la requte est locale et qu'il n'y a pas de session, on ignore la vrification { System.out.println("IP OK: bypass"); } /// On rcupre le noeud de la ressource pour retrouver le lien String data = dataProvider.getResNode(uuid, userId, groupId); // javax.servlet.http.HttpSession session = request.getSession(true); //==================================================== //String ppath = session.getServletContext().getRealPath("/"); //logFName = ppath +"logs/logNode.txt"; //==================================================== String size = request.getParameter("size"); if (size == null) size = "S"; String lang = request.getParameter("lang"); if (lang == null) { lang = "fr"; } /* String nodeUuid = uri.substring(uri.lastIndexOf("/")+1); if (uri.lastIndexOf("/")>uri.indexOf("file/")+6) { // -- file/ = 5 carac. -- lang = uri.substring(uri.indexOf("file/")+5,uri.lastIndexOf("/")); } //*/ String ref = request.getHeader("referer"); /// Parse les donnes DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader("<node>" + data + "</node>")); Document doc = documentBuilder.parse(is); DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0"); LSSerializer serial = impl.createLSSerializer(); serial.getDomConfig().setParameter("xml-declaration", false); /// Trouve le bon noeud XPath xPath = XPathFactory.newInstance().newXPath(); /// Either we have a fileid per language String filterRes = "//fileid[@lang='" + lang + "']"; NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET); String resolve = ""; if (nodelist.getLength() != 0) { Element fileNode = (Element) nodelist.item(0); resolve = fileNode.getTextContent(); } /// Or just a single one shared if ("".equals(resolve)) { response.setStatus(404); return; } String filterName = "//filename[@lang='" + lang + "']"; NodeList textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET); String filename = ""; if (textList.getLength() != 0) { Element fileNode = (Element) textList.item(0); filename = fileNode.getTextContent(); } String filterType = "//type[@lang='" + lang + "']"; textList = (NodeList) xPath.compile(filterType).evaluate(doc, XPathConstants.NODESET); String type = ""; if (textList.getLength() != 0) { Element fileNode = (Element) textList.item(0); type = fileNode.getTextContent(); } /* String filterSize = "//size[@lang='"+lang+"']"; textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET); String filesize = ""; if( textList.getLength() != 0 ) { Element fileNode = (Element) textList.item(0); filesize = fileNode.getTextContent(); } //*/ System.out.println("!!! RESOLVE: " + resolve); /// Envoie de la requte au servlet de fichiers // http://localhost:8080/MiniRestFileServer/user/claudecoulombe/file/a8e0f07f-671c-4f6a-be6c-9dba12c519cf/ptype/sql /// TODO: Ne plus avoir besoin du switch String urlTarget = "http://" + server + "/" + resolve; // String urlTarget = "http://"+ server + "/user/" + resolve +"/"+ lang + "/ptype/fs"; HttpURLConnection connection = CreateConnection(urlTarget, request); connection.connect(); InputStream input = connection.getInputStream(); String sizeComplete = connection.getHeaderField("Content-Length"); int completeSize = Integer.parseInt(sizeComplete); response.setContentLength(completeSize); response.setContentType(type); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); ServletOutputStream output = response.getOutputStream(); byte[] buffer = new byte[completeSize]; int totalRead = 0; int bytesRead = -1; while ((bytesRead = input.read(buffer, 0, completeSize)) != -1 || totalRead < completeSize) { output.write(buffer, 0, bytesRead); totalRead += bytesRead; } // IOUtils.copy(input, output); // IOUtils.closeQuietly(output); output.flush(); output.close(); input.close(); connection.disconnect(); } catch (RestWebApplicationException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { logger.error(e.toString() + " -> " + e.getLocalizedMessage()); e.printStackTrace(); //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile: error"+e); } finally { try { dataProvider.disconnect(); } catch (Exception e) { ServletOutputStream out = response.getOutputStream(); out.println("Erreur dans doGet: " + e); out.close(); } } }
From source file:cw.kop.autobackground.files.DownloadThread.java
private Bitmap getImage(String url) { if (Patterns.WEB_URL.matcher(url).matches()) { try {//w ww .jav a 2 s . com int minWidth = AppSettings.getImageWidth(); int minHeight = AppSettings.getImageHeight(); System.gc(); URL imageUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection(); connection.connect(); InputStream input = connection.getInputStream(); if (!connection.getHeaderField("Content-Type").startsWith("image/") && !AppSettings.forceDownload()) { Log.i(TAG, "Not an image: " + url); return null; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.inJustDecodeBounds = true; if (!AppSettings.useHighQuality()) { options.inPreferredConfig = Bitmap.Config.RGB_565; } BitmapFactory.decodeStream(input, null, options); input.close(); int bitWidth = options.outWidth; int bitHeight = options.outHeight; options.inJustDecodeBounds = false; Log.i(TAG, "bitWidth: " + bitWidth + " bitHeight: " + bitHeight); if (bitWidth + 10 < minWidth || bitHeight + 10 < minHeight) { return null; } int sampleSize = 1; if (!AppSettings.useFullResolution()) { if (bitHeight > minHeight || bitWidth > minWidth) { final int halfHeight = bitHeight / 2; final int halfWidth = bitWidth / 2; while ((halfHeight / sampleSize) > minHeight && (halfWidth / sampleSize) > minWidth) { sampleSize *= 2; } } } options.inSampleSize = sampleSize; connection = (HttpURLConnection) imageUrl.openConnection(); connection.setConnectTimeout(5000); connection.setConnectTimeout(30000); connection.connect(); input = connection.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(input, null, options); if (bitmap == null) { Log.i(TAG, "Null bitmap"); return null; } return bitmap; } catch (InterruptedIOException e) { this.interrupt(); Log.i(TAG, "Interrupted"); } catch (OutOfMemoryError | IOException e) { interrupt(); e.printStackTrace(); } } Log.i(TAG, "Possible malformed URL"); return null; }
From source file:com.fastbootmobile.encore.api.common.HttpGet.java
/** * Downloads the data from the provided URL. * @param inUrl The URL to get from/*from ww w.ja va 2s .c o m*/ * @param query The query field. '?' + query will be appended automatically, and the query data * MUST be encoded properly. * @return A byte array of the data */ public static byte[] getBytes(String inUrl, String query, boolean cached) throws IOException, RateLimitException { final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query)); Log.d(TAG, "Formatted URL: " + formattedUrl); URL url = new URL(formattedUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)"); urlConnection.setUseCaches(cached); urlConnection.setInstanceFollowRedirects(true); int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale); try { final int status = urlConnection.getResponseCode(); // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway. if (status == HttpURLConnection.HTTP_OK) { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); int contentLength = urlConnection.getContentLength(); if (contentLength <= 0) { // No length? Let's allocate 100KB. contentLength = 100 * 1024; } ByteArrayBuffer bab = new ByteArrayBuffer(contentLength); BufferedInputStream bis = new BufferedInputStream(in); int character; while ((character = bis.read()) != -1) { bab.append(character); } return bab.toByteArray(); } else if (status == HttpURLConnection.HTTP_NOT_FOUND) { // 404 return new byte[] {}; } else if (status == HttpURLConnection.HTTP_FORBIDDEN) { return new byte[] {}; } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) { throw new RateLimitException(); } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */ || status == HttpURLConnection.HTTP_SEE_OTHER) { // We've been redirected, follow the new URL final String followUrl = urlConnection.getHeaderField("Location"); Log.e(TAG, "Redirected to: " + followUrl); return getBytes(followUrl, "", cached); } else { Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")"); return new byte[] {}; } } finally { urlConnection.disconnect(); } }
From source file:com.ris.mobile.ecloud.util.AbFileUtil.java
/** * ????.//from www .ja v a 2 s .co m * @param url ? * @return ?? */ public static String getRealFileNameFromUrl(String url) { String name = null; try { if (AbStrUtil.isEmpty(url)) { return name; } URL mUrl = new URL(url); HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection(); mHttpURLConnection.setConnectTimeout(5 * 1000); mHttpURLConnection.setRequestMethod("GET"); mHttpURLConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN"); mHttpURLConnection.setRequestProperty("Referer", url); mHttpURLConnection.setRequestProperty("Charset", "UTF-8"); mHttpURLConnection.setRequestProperty("User-Agent", ""); mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive"); mHttpURLConnection.connect(); if (mHttpURLConnection.getResponseCode() == 200) { for (int i = 0;; i++) { String mine = mHttpURLConnection.getHeaderField(i); if (mine == null) { break; } if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) { Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase()); if (m.find()) return m.group(1).replace("\"", ""); } } } } catch (Exception e) { e.printStackTrace(); // AbLogUtil.e(AbFileUtil.class, "???"); } return name; }
From source file:cc.arduino.utils.network.FileDownloader.java
private void downloadFile(boolean noResume) throws InterruptedException { RandomAccessFile file = null; try {//from w w w . j av a 2 s. co m // Open file and seek to the end of it file = new RandomAccessFile(outputFile, "rw"); initialSize = file.length(); if (noResume && initialSize > 0) { // delete file and restart downloading Files.delete(outputFile.toPath()); initialSize = 0; } file.seek(initialSize); setStatus(Status.CONNECTING); Proxy proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(downloadUrl.toURI()); if ("true".equals(System.getProperty("DEBUG"))) { System.err.println("Using proxy " + proxy); } HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(proxy); connection.setRequestProperty("User-agent", userAgent); if (downloadUrl.getUserInfo() != null) { String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes())); connection.setRequestProperty("Authorization", auth); } connection.setRequestProperty("Range", "bytes=" + initialSize + "-"); connection.setConnectTimeout(5000); setDownloaded(0); // Connect connection.connect(); int resp = connection.getResponseCode(); if (resp == HttpURLConnection.HTTP_MOVED_PERM || resp == HttpURLConnection.HTTP_MOVED_TEMP) { URL newUrl = new URL(connection.getHeaderField("Location")); proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(newUrl.toURI()); // open the new connnection again connection = (HttpURLConnection) newUrl.openConnection(proxy); connection.setRequestProperty("User-agent", userAgent); if (downloadUrl.getUserInfo() != null) { String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes())); connection.setRequestProperty("Authorization", auth); } connection.setRequestProperty("Range", "bytes=" + initialSize + "-"); connection.setConnectTimeout(5000); connection.connect(); resp = connection.getResponseCode(); } if (resp < 200 || resp >= 300) { throw new IOException("Received invalid http status code from server: " + resp); } // Check for valid content length. long len = connection.getContentLength(); if (len >= 0) { setDownloadSize(len); } setStatus(Status.DOWNLOADING); synchronized (this) { stream = connection.getInputStream(); } byte buffer[] = new byte[10240]; while (status == Status.DOWNLOADING) { int read = stream.read(buffer); if (read == -1) break; file.write(buffer, 0, read); setDownloaded(getDownloaded() + read); if (Thread.interrupted()) { file.close(); throw new InterruptedException(); } } if (getDownloadSize() != null) { if (getDownloaded() < getDownloadSize()) throw new Exception("Incomplete download"); } setStatus(Status.COMPLETE); } catch (InterruptedException e) { setStatus(Status.CANCELLED); // lets InterruptedException go up to the caller throw e; } catch (SocketTimeoutException e) { setStatus(Status.CONNECTION_TIMEOUT_ERROR); setError(e); } catch (Exception e) { setStatus(Status.ERROR); setError(e); } finally { IOUtils.closeQuietly(file); synchronized (this) { IOUtils.closeQuietly(stream); } } }
From source file:com.bnrc.util.AbFileUtil.java
/** * ????.//from w ww . j a v a 2 s .c o m * @param url ??? * @return ?? */ public static String getRealFileNameFromUrl(String url) { String name = null; try { if (AbStrUtil.isEmpty(url)) { return name; } URL mUrl = new URL(url); HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection(); mHttpURLConnection.setConnectTimeout(5 * 1000); mHttpURLConnection.setRequestMethod("GET"); mHttpURLConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN"); mHttpURLConnection.setRequestProperty("Referer", url); mHttpURLConnection.setRequestProperty("Charset", "UTF-8"); mHttpURLConnection.setRequestProperty("User-Agent", ""); mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive"); mHttpURLConnection.connect(); if (mHttpURLConnection.getResponseCode() == 200) { for (int i = 0;; i++) { String mine = mHttpURLConnection.getHeaderField(i); if (mine == null) { break; } if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) { Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase()); if (m.find()) return m.group(1).replace("\"", ""); } } } } catch (Exception e) { e.printStackTrace(); AbLogUtil.e(AbFileUtil.class, "??"); } return name; }
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 {//from w w w . j a va 2s .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.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 . j a 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(); 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(); } } }