List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBody
public abstract byte[] getResponseBody() throws IOException;
From source file:org.lareferencia.backend.rest.BackEndController.java
@ResponseBody @RequestMapping(value = "/public/harvestMetadataByRecordID/{id}", method = RequestMethod.GET) public String harvestyMetadataByRecordID(@PathVariable Long id) throws Exception { OAIRecord record = recordRepository.findOne(id); String result = ""; if (record != null) { Network network = record.getSnapshot().getNetwork(); ArrayList<OAIOrigin> origins = new ArrayList<>(network.getOrigins()); String oaiURLBase = origins.get(0).getUri(); String recordURL = oaiURLBase + "?verb=GetRecord&metadataPrefix=oai_dc&identifier=" + record.getIdentifier(); HttpClient client = new HttpClient(); client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpMethod method = new GetMethod(recordURL); int responseCode = client.executeMethod(method); if (responseCode != 200) { throw new HttpException( "HttpMethod Returned Status Code: " + responseCode + " when attempting: " + recordURL); }//from w w w . ja v a 2 s . com result = new String(method.getResponseBody(), "UTF-8"); } return result; }
From source file:org.melati.admin.Admin.java
private String proxy(Melati melati, ServletTemplateContext context) { if (melati.getSession().getAttribute("generatedByMelatiClass") == null) throw new AnticipatedException("Only available from within an Admin generated page"); String method = melati.getRequest().getMethod(); String url = melati.getRequest().getQueryString(); HttpServletResponse response = melati.getResponse(); HttpMethod httpMethod = null; try {// w ww . j av a2 s.c om HttpClient client = new HttpClient(); if (method.equals("GET")) httpMethod = new GetMethod(url); else if (method.equals("POST")) httpMethod = new PostMethod(url); else if (method.equals("PUT")) httpMethod = new PutMethod(url); else if (method.equals("HEAD")) httpMethod = new HeadMethod(url); else throw new RuntimeException("Unexpected method '" + method + "'"); try { httpMethod.setFollowRedirects(true); client.executeMethod(httpMethod); for (Header h : httpMethod.getResponseHeaders()) { response.setHeader(h.getName(), h.getValue()); } response.setStatus(httpMethod.getStatusCode()); response.setHeader("Cache-Control", "no-cache"); byte[] outputBytes = httpMethod.getResponseBody(); if (outputBytes != null) { response.setBufferSize(outputBytes.length); response.getWriter().write(new String(outputBytes)); response.getWriter().flush(); } } catch (Exception e) { throw new MelatiIOException(e); } } finally { if (httpMethod != null) httpMethod.releaseConnection(); } return null; }
From source file:org.methodize.nntprss.feed.Channel.java
/** * Executes HTTP request/* www . jav a2 s. c om*/ * @param client * @param config * @param method */ private static HttpResult executeHttpRequest(HttpClient client, HostConfiguration config, HttpMethod method) throws HttpException, IOException { HttpResult result; int statusCode = -1; try { statusCode = client.executeMethod(config, method); // while (statusCode == -1 && attempt < 3) { // try { // // execute the method. // statusCode = client.executeMethod(config, method); // } catch (HttpRecoverableException e) { // log.( // "A recoverable exception occurred, retrying." // + e.getMessage()); // method.releaseConnection(); // method.recycle(); // try { // Thread.sleep(250); // } catch(InterruptedException ie) { // } // } // } result = new HttpResult(statusCode); Header locationHeader = method.getResponseHeader("location"); if (locationHeader != null) { result.setLocation(locationHeader.getValue()); } if (statusCode == HttpStatus.SC_OK) { Header contentEncoding = method.getResponseHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equals("gzip")) { InputStream is = method.getResponseBodyAsStream(); is = new GZIPInputStream(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = is.read(buf)) > -1) { if (bytesRead > 0) { baos.write(buf, 0, bytesRead); } } baos.flush(); baos.close(); is.close(); result.setResponse(baos.toByteArray()); } else { result.setResponse(method.getResponseBody()); } } else { // Process response InputStream is = method.getResponseBodyAsStream(); if (is != null) { byte[] buf = new byte[1024]; while (is.read(buf) != -1) ; is.close(); } // result.setResponse(method.getResponseBody()); } return result; } finally { method.releaseConnection(); } }
From source file:org.nunux.poc.portal.ProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * * @param httpMethodProxyRequest An object representing the proxy request to * be made// ww w. j a va 2 s .c om * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has * occurred */ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { if (httpServletRequest.isSecure()) { Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443)); } // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); InputStream response = httpMethodProxyRequest.getResponseBodyAsStream(); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* * 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* * 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); if (followRedirects) { if (stringLocation.contains("jsessionid")) { Cookie cookie = new Cookie("JSESSIONID", stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11)); cookie.setPath("/"); httpServletResponse.addCookie(cookie); //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL"); } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) { Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie"); String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); if (nameValue[0].equalsIgnoreCase("jsessionid")) { httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(), nameValue[1]); debug("redirecting: store jsessionid: " + nameValue[1]); } else { Cookie cookie = new Cookie(nameValue[0], nameValue[1]); cookie.setPath("/"); //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath()); httpServletResponse.addCookie(cookie); } } httpServletResponse.sendRedirect( stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName)); return; } } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked") || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth // proxy servlet does not support chunked encoding } else if (header.getName().equals("Set-Cookie")) { String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); if (nameValue[0].equalsIgnoreCase("jsessionid")) { httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(), nameValue[1]); debug("redirecting: store jsessionid: " + nameValue[1]); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } List<Header> responseHeaders = Arrays.asList(headerArrayResponse); if (isBodyParameterGzipped(responseHeaders)) { debug("GZipped: true"); int length = 0; if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) { String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); intProxyResponseCode = HttpServletResponse.SC_OK; httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz); } else { final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody()); length = bytes.length; response = new ByteArrayInputStream(bytes); } httpServletResponse.setContentLength(length); } // Send the content to the client debug("Received status code: " + intProxyResponseCode, "Response: " + response); //httpServletResponse.getWriter().write(response); copy(response, httpServletResponse.getOutputStream()); }
From source file:org.openqa.selenium.remote.HttpCommandExecutor.java
private Response createResponse(HttpMethod httpMethod) throws Exception { Response response;//from w w w . ja va 2s .c om Header header = httpMethod.getResponseHeader("Content-Type"); if (header != null && header.getValue().startsWith("application/json")) { response = new JsonToBeanConverter().convert(Response.class, httpMethod.getResponseBodyAsString()); } else { response = new Response(); if (header != null && header.getValue().startsWith("image/png")) { response.setValue(httpMethod.getResponseBody()); } else { response.setValue(httpMethod.getResponseBodyAsString()); } String uri = httpMethod.getURI().toString(); int sessionIndex = uri.indexOf("/session/"); if (sessionIndex != -1) { sessionIndex += "/session/".length(); int nextSlash = uri.indexOf("/", sessionIndex); if (nextSlash != -1) { response.setSessionId(uri.substring(sessionIndex, nextSlash)); response.setContext("foo"); } } } response.setError(!(httpMethod.getStatusCode() > 199 && httpMethod.getStatusCode() < 300)); if (response.getValue() instanceof String) { //We normalise to \n because Java will translate this to \r\n //if this is suitable on our platform, and if we have \r\n, java will //turn this into \r\r\n, which would be Bad! response.setValue(((String) response.getValue()).replace("\r\n", "\n")); } return response; }
From source file:org.parosproxy.paros.network.HttpSender.java
private void send(HttpMessage msg, boolean isFollowRedirect) throws IOException { HttpMethod method = null; HttpResponseHeader resHeader = null; try {/*www . ja va 2 s . c o m*/ method = runMethod(msg, isFollowRedirect); // successfully executed; resHeader = HttpMethodHelper.getHttpResponseHeader(method); resHeader.setHeader(HttpHeader.TRANSFER_ENCODING, null); // replaceAll("Transfer-Encoding: chunked\r\n", // ""); msg.setResponseHeader(resHeader); msg.getResponseBody().setCharset(resHeader.getCharset()); msg.getResponseBody().setLength(0); // ZAP: Do not read response body for Server-Sent Events stream // ZAP: Moreover do not set content length to zero if (!msg.isEventStream()) { msg.getResponseBody().append(method.getResponseBody()); } msg.setResponseFromTargetHost(true); // ZAP: set method to retrieve upgraded channel later if (method instanceof ZapGetMethod) { msg.setUserObject(method); } } finally { if (method != null) { method.releaseConnection(); } } }
From source file:org.qifu.sys.CxfServerBean.java
@SuppressWarnings("unchecked") public static Map<String, Object> shutdownOrReloadCallOneSystem(HttpServletRequest request, String system, String type) throws ServiceException, Exception { if (StringUtils.isBlank(system) || StringUtils.isBlank(type)) { throw new ServiceException(SysMessageUtil.get(SysMsgConstants.PARAMS_BLANK)); }/*ww w . ja va 2s. co m*/ String urlStr = ApplicationSiteUtils.getBasePath(system, request) + "config-services?type=" + type + "&value=" + createParamValue(); logger.info("shutdownOrReloadCallSystem , url=" + urlStr); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(urlStr); client.executeMethod(method); byte[] responseBody = method.getResponseBody(); if (null == responseBody) { throw new Exception("no response!"); } String content = new String(responseBody, Constants.BASE_ENCODING); logger.info("shutdownOrReloadCallSystem , system=" + system + " , type=" + type + " , response=" + content); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> dataMap = null; try { dataMap = (Map<String, Object>) mapper.readValue(content, HashMap.class); } catch (JsonParseException e) { logger.error(e.getMessage().toString()); } catch (JsonMappingException e) { logger.error(e.getMessage().toString()); } if (null == dataMap) { throw new Exception("response content error!"); } return dataMap; }
From source file:org.qifu.util.ApplicationSiteUtils.java
private static boolean checkTestConnection(String host, String contextPath, HttpServletRequest request) { boolean test = false; String basePath = request.getScheme() + "://" + host + "/" + contextPath; String urlStr = basePath + "/pages/system/testJsonResult.do"; try {//from w w w.j a va2 s .c om logger.info("checkTestConnection , url=" + urlStr); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(urlStr); HttpClientParams params = new HttpClientParams(); params.setConnectionManagerTimeout(TEST_JSON_HTTP_TIMEOUT); params.setSoTimeout(TEST_JSON_HTTP_TIMEOUT); client.setParams(params); client.executeMethod(method); byte[] responseBody = method.getResponseBody(); if (null == responseBody) { test = false; return test; } String content = new String(responseBody, Constants.BASE_ENCODING); ObjectMapper mapper = new ObjectMapper(); @SuppressWarnings("unchecked") Map<String, Object> dataMap = (Map<String, Object>) mapper.readValue(content, HashMap.class); if (YesNo.YES.equals(dataMap.get("success"))) { test = true; } } catch (JsonParseException e) { logger.error(e.getMessage().toString()); } catch (JsonMappingException e) { logger.error(e.getMessage().toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (!test) { logger.warn("checkTestConnection : " + String.valueOf(test)); } else { logger.info("checkTestConnection : " + String.valueOf(test)); } } return test; }
From source file:org.red5.server.service.Installer.java
/** * Installs a given application./* w w w. ja va 2s. c o m*/ * * @param applicationWarName app war name * @return true if installed; false otherwise */ public boolean install(String applicationWarName) { IConnection conn = Red5.getConnectionLocal(); boolean result = false; //strip everything except the applications name String application = applicationWarName.substring(0, applicationWarName.indexOf('-')); log.debug("Application name: {}", application); //get webapp location String webappsDir = System.getProperty("red5.webapp.root"); log.debug("Webapp folder: {}", webappsDir); //setup context String contextPath = '/' + application; String contextDir = webappsDir + contextPath; //verify this is a unique app File appDir = new File(webappsDir, application); if (appDir.exists()) { if (appDir.isDirectory()) { log.debug("Application directory exists"); } else { log.warn("Application destination is not a directory"); } ServiceUtils.invokeOnConnection(conn, "onAlert", new Object[] { String.format( "Application %s already installed, please un-install before attempting another install", application) }); } else { //use the system temp directory for moving files around String srcDir = System.getProperty("java.io.tmpdir"); log.debug("Source directory: {}", srcDir); //look for archive containing application (war, zip, etc..) File dir = new File(srcDir); if (!dir.exists()) { log.warn("Source directory not found"); //use another directory dir = new File(System.getProperty("red5.root"), "/webapps/installer/WEB-INF/cache"); if (!dir.exists()) { if (dir.mkdirs()) { log.info("Installer cache directory created"); } } } else { if (!dir.isDirectory()) { log.warn("Source directory is not a directory"); } } //get a list of temp files File[] files = dir.listFiles(); for (File f : files) { String fileName = f.getName(); if (fileName.equals(applicationWarName)) { log.debug("File found matching application name"); result = true; break; } } dir = null; //if the file was not found then download it if (!result) { // create a singular HttpClient object HttpClient client = new HttpClient(); // set the proxy (WT) if ((System.getProperty("http.proxyHost") != null) && (System.getProperty("http.proxyPort") != null)) { HostConfiguration config = client.getHostConfiguration(); config.setProxy(System.getProperty("http.proxyHost").toString(), Integer.parseInt(System.getProperty("http.proxyPort"))); } // establish a connection within 5 seconds client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); //get the params for the client HttpClientParams params = client.getParams(); params.setParameter(HttpMethodParams.USER_AGENT, userAgent); params.setParameter(HttpMethodParams.STRICT_TRANSFER_ENCODING, Boolean.TRUE); //try the wav version first HttpMethod method = new GetMethod(applicationRepositoryUrl + applicationWarName); //we dont want any transformation - RFC2616 method.addRequestHeader("Accept-Encoding", "identity"); //follow any 302's although there shouldnt be any method.setFollowRedirects(true); FileOutputStream fos = null; // execute the method try { int code = client.executeMethod(method); log.debug("HTTP response code: {}", code); //create output file fos = new FileOutputStream(srcDir + '/' + applicationWarName); log.debug("Writing response to {}/{}", srcDir, applicationWarName); // have to receive the response as a byte array. This has the advantage of writing to the filesystem // faster and it also works on macs ;) byte[] buf = method.getResponseBody(); fos.write(buf); fos.flush(); result = true; } catch (HttpException he) { log.error("Http error connecting to {}", applicationRepositoryUrl, he); } catch (IOException ioe) { log.error("Unable to connect to {}", applicationRepositoryUrl, ioe); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } if (method != null) { method.releaseConnection(); } } } //if we've found or downloaded the war if (result) { //get the webapp loader LoaderMBean loader = getLoader(); if (loader != null) { //un-archive it to app dir FileUtil.unzip(srcDir + '/' + applicationWarName, contextDir); //load and start the context loader.startWebApplication(application); } else { //just copy the war to the webapps dir try { FileUtil.moveFile(srcDir + '/' + applicationWarName, webappsDir + '/' + application + ".war"); ServiceUtils.invokeOnConnection(conn, "onAlert", new Object[] { String.format( "Application %s will not be available until container is restarted", application) }); } catch (IOException e) { } } } ServiceUtils.invokeOnConnection(conn, "onAlert", new Object[] { String.format("Application %s was %s", application, (result ? "installed" : "not installed")) }); } appDir = null; return result; }
From source file:org.semispace.google.space.address.FetchAddress.java
public GoogleAddress resolveAddress(String address, GoogleKey key) { GoogleAddress result = new GoogleAddress(); String url = encodeAddressAsHttpParameter(address, key); log.debug("Query url: " + url); HttpMethod method = new GetMethod(url); try {/*w w w. java2s . c o m*/ result.setAddress(address); HttpClient client = new HttpClient(); method.setFollowRedirects(false); method.setDoAuthentication(false); client.executeMethod(method); byte[] buffer = method.getResponseBody(); fillResponseInAddress(result, new String(buffer)); } catch (IOException e) { result.setStatusCode("-1"); log.error("Got exception", e); } finally { method.releaseConnection(); } return result; }