List of usage examples for org.apache.commons.httpclient HttpMethodBase getResponseBody
@Override public byte[] getResponseBody() throws IOException
From source file:org.eclipse.php.composer.core.HttpHelper.java
public static String executeGetRequest(String url, Map<String, String> parameters, Map<String, String> cookies, int expectedCode) { try {/*from www. j a va2 s . c om*/ HttpClient client = createHttpClient(url, ComposerCorePlugin.getProxyService()); HttpMethodBase method = createGetRequest(url, parameters); setCookies(method, cookies); if (method != null) { int statusCode = -1; try { statusCode = client.executeMethod(method); if (statusCode == expectedCode) { String responseContent = new String(method.getResponseBody()); return responseContent; } } finally { method.releaseConnection(); } } } catch (IOException e) { ComposerCorePlugin.logError(e); } catch (URISyntaxException e) { ComposerCorePlugin.logError(e); } return null; }
From source file:org.elasticsearch.hadoop.rest.RestClient.java
byte[] execute(HttpMethodBase method, boolean checkStatus) { try {//from w w w. j a v a 2 s . c om int status = client.executeMethod(method); if (checkStatus && status >= HttpStatus.SC_MULTI_STATUS) { String body; try { body = method.getResponseBodyAsString(); } catch (IOException ex) { body = ""; } throw new IllegalStateException(String.format("[%s] on [%s] failed; server[%s] returned [%s]", method.getName(), method.getURI(), client.getHostConfiguration().getHostURL(), body)); } return method.getResponseBody(); } catch (IOException io) { String target; try { target = method.getURI().toString(); } catch (IOException ex) { target = method.getPath(); } throw new IllegalStateException( String.format("Cannot get response body for [%s][%s]", method.getName(), target)); } finally { method.releaseConnection(); } }
From source file:org.fao.oaipmh.requests.Transport.java
private Element doExecute(HttpMethodBase httpMethod) throws IOException, JDOMException { config.setHost(host, port, Protocol.getProtocol(protocol)); if (useProxy) config.setProxy(proxyHost, proxyPort); byte[] data = null; try {// ww w .ja v a 2 s . c o m client.executeMethod(httpMethod); data = httpMethod.getResponseBody(); Element response = Xml.loadStream(new ByteArrayInputStream(data)); setupSentData(httpMethod); setupReceivedData(httpMethod, data); return response; } finally { httpMethod.releaseConnection(); } }
From source file:org.genemania.util.HttpRetriever.java
public String post(String url, Hashtable<String, String> params) { String ret = ""; try {//ww w . j av a 2s . c o m HttpClient client = new HttpClient(); HttpMethodBase method = new PostMethod(url); Enumeration<String> paramNames = params.keys(); while (paramNames.hasMoreElements()) { String nextParamName = paramNames.nextElement(); String nextParamValue = params.get(nextParamName); ((PostMethod) (method)).addParameter(nextParamName, nextParamValue); } int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println("HttpRetriever error: " + method.getStatusLine()); } else { byte[] responseBody = method.getResponseBody(); method.releaseConnection(); ret = new String(responseBody); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ret; }
From source file:org.opentides.util.UrlUtil.java
/** * Returns the HTML code of the original engine. Takes the URL to connect to * the engine. Also takes encoding type that overrides default if not null * "UTF8" is typical encoding type/* w ww . j av a2 s .c o m*/ * * @param queryURL * - URL of engine to retrieve * @param request * - request object * @param param * - additional parameters * - Valid parameters are: * - methodName - Either "POST" or "GET". Default is "POST" * - forwardCookie - if true, will forward cookies found on request object * - IPAddress - if specified, this IP will be used for the request * */ public static final UrlResponseObject getPage(final String queryURL, final HttpServletRequest request, final Map<String, Object> param) { // determine if get or post method HttpMethodBase httpMethodBase; Boolean forwardCookie = false; InetAddress IPAddress = null; if (param != null) { if (param.get("forwardCookie") != null) forwardCookie = (Boolean) param.get("forwardCookie"); if (param.get("IPAddress") != null) { String IPString = (String) param.get("IPAddress"); if (!StringUtil.isEmpty(IPString)) { IPAddress = convertIPString(IPString); } } } if (param != null && "GET".equals((String) param.get("methodName"))) { httpMethodBase = new GetMethod(queryURL); } else { httpMethodBase = new PostMethod(queryURL); } try { // declare the connection objects HttpClient client = new HttpClient(); HostConfiguration hostConfig = new HostConfiguration(); String userAgent = request.getHeader("User-Agent"); // for debugging if (_log.isDebugEnabled()) _log.debug("Retrieving page from " + queryURL); // initialize the connection settings client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT); client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); httpMethodBase.addRequestHeader("accept", "*/*"); httpMethodBase.addRequestHeader("accept-language", "en-us"); httpMethodBase.addRequestHeader("user-agent", userAgent); if (forwardCookie) { // get cookies from request Cookie[] cookies = request.getCookies(); String cookieString = ""; for (Cookie c : cookies) { cookieString += c.getName() + "=" + c.getValue() + "; "; } // forward cookies to httpMethod httpMethodBase.setRequestHeader("Cookie", cookieString); } if (IPAddress != null) { hostConfig.setLocalAddress(IPAddress); } // Setup for 3 retry httpMethodBase.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // now let's retrieve the data client.executeMethod(hostConfig, httpMethodBase); // Read the response body. UrlResponseObject response = new UrlResponseObject(); response.setResponseBody(httpMethodBase.getResponseBody()); Header contentType = httpMethodBase.getResponseHeader("Content-Type"); if (contentType != null) response.setResponseType(contentType.getValue()); else response.setResponseType(Widget.TYPE_HTML); return response; } catch (Exception ex) { _log.error("Failed to request from URL: [" + queryURL + "]", ex); return null; } finally { try { httpMethodBase.releaseConnection(); } catch (Exception ignored) { } } }
From source file:org.opentides.util.WidgetUtil.java
/** * Returns the HTML code of the original engine. Takes the URL to connect to * the engine. Also takes encoding type that overrides default if not null * "UTF8" is typical encoding type/*from w w w. j a va2 s . co m*/ * * @param queryURL * - URL of engine to retrieve * @param request * - request object * @param param * - additional parameters * - Valid parameters are: * - methodName - Either "POST" or "GET". Default is "POST" * - forwardCookie - if true, will forward cookies found on request object * - IPAddress - if specified, this IP will be used for the request * */ public static final UrlResponseObject getPage(final String queryURL, final HttpServletRequest request, final Map<String, Object> param) { // determine if get or post method HttpMethodBase httpMethodBase; Boolean forwardCookie = false; InetAddress IPAddress = null; if (param != null) { if (param.get("forwardCookie") != null) forwardCookie = (Boolean) param.get("forwardCookie"); if (param.get("IPAddress") != null) { String IPString = (String) param.get("IPAddress"); if (!StringUtil.isEmpty(IPString)) { IPAddress = UrlUtil.convertIPString(IPString); } } } if (param != null && "GET".equals((String) param.get("methodName"))) { httpMethodBase = new GetMethod(queryURL); } else { httpMethodBase = new PostMethod(queryURL); } try { // declare the connection objects HttpClient client = new HttpClient(); HostConfiguration hostConfig = new HostConfiguration(); String userAgent = request.getHeader("User-Agent"); // for debugging if (_log.isDebugEnabled()) _log.debug("Retrieving page from " + queryURL); // initialize the connection settings client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT); client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); httpMethodBase.addRequestHeader("accept", "*/*"); httpMethodBase.addRequestHeader("accept-language", "en-us"); httpMethodBase.addRequestHeader("user-agent", userAgent); if (forwardCookie) { // get cookies from request Cookie[] cookies = request.getCookies(); String cookieString = ""; for (Cookie c : cookies) { cookieString += c.getName() + "=" + c.getValue() + "; "; } // forward cookies to httpMethod httpMethodBase.setRequestHeader("Cookie", cookieString); } if (IPAddress != null) { hostConfig.setLocalAddress(IPAddress); } // Setup for 3 retry httpMethodBase.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // now let's retrieve the data client.executeMethod(hostConfig, httpMethodBase); // Read the response body. UrlResponseObject response = new UrlResponseObject(); response.setResponseBody(httpMethodBase.getResponseBody()); Header contentType = httpMethodBase.getResponseHeader("Content-Type"); if (contentType != null) response.setResponseType(contentType.getValue()); else response.setResponseType("html"); return response; } catch (Exception ex) { _log.error("Failed to request from URL: [" + queryURL + "]", ex); return null; } finally { try { httpMethodBase.releaseConnection(); } catch (Exception ignored) { } } }
From source file:org.tinygroup.httpvisit.impl.HttpVisitorImpl.java
String execute(HttpMethodBase method) { try {//from w w w .j a v a 2s.c o m if (client == null) { init(); } LOGGER.logMessage(LogLevel.DEBUG, "?:{}", method.getURI().toString()); if (!("ISO-8859-1").equals(requestCharset)) { method.addRequestHeader("Content-Type", "text/html; charset=" + requestCharset); } method.setDoAuthentication(authEnabled); int iGetResultCode = client.executeMethod(method); if (iGetResultCode == HttpStatus.SC_OK) { LOGGER.logMessage(LogLevel.DEBUG, "?"); Header responseHeader = method.getResponseHeader("Content-Encoding"); if (responseHeader != null) { String acceptEncoding = responseHeader.getValue(); if (acceptEncoding != null && ("gzip").equals(acceptEncoding)) { //gzip? ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( method.getResponseBody()); GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream); return IOUtils.readFromInputStream(gzipInputStream, responseCharset); } } return new String(method.getResponseBody(), responseCharset); } LOGGER.logMessage(LogLevel.ERROR, "{}", method.getStatusLine().toString()); throw new RuntimeException(method.getStatusLine().toString()); } catch (Exception e) { LOGGER.logMessage(LogLevel.DEBUG, "{}", e.getMessage()); throw new RuntimeException(e); } finally { method.releaseConnection(); } }
From source file:org.zend.php.zendserver.deployment.core.targets.OpenShiftTargetInitializer.java
private String executeGet(String url, Map<String, String> cookies) { HttpClient client = new HttpClient(); HttpMethodBase method = createGetRequest(url, new HashMap<String, String>()); setCookies(method, cookies);//from www .ja v a 2s. co m if (method != null) { int statusCode = -1; try { statusCode = client.executeMethod(method); if (statusCode == 200) { String responseContent = new String(method.getResponseBody()); return responseContent; } } catch (IOException e) { DeploymentCore.log(e); } finally { method.releaseConnection(); } return null; } return null; }
From source file:org.zend.sdklib.internal.target.ApiKeyDetector.java
private boolean isBootstrapped() throws SdkException { HttpClient client = new HttpClient(); HttpMethodBase method = new GetMethod(getUrl("/Login")); //$NON-NLS-1$ if (method != null) { int statusCode = -1; try {//from ww w. ja v a2 s.co m statusCode = client.executeMethod(method); if (statusCode == 200) { String responseContent = new String(method.getResponseBody()); if (!responseContent.contains("BootstrapWizard")) { //$NON-NLS-1$ return true; } } } catch (IOException e) { throw new SdkException(e); } finally { method.releaseConnection(); } } return false; }
From source file:org.zend.sdklib.internal.target.ApiKeyDetector.java
private String executeAddApiKey(String url, Map<String, String> params, Map<String, String> cookies) throws SdkException { HttpClient client = new HttpClient(); HttpMethodBase method = createPostRequest(url, params); setCookies(method, cookies);// w ww. ja v a 2 s . com method.setRequestHeader("X-Accept", //$NON-NLS-1$ "application/vnd.zend.serverapi+json;version=1.3;q=1.0"); //$NON-NLS-1$ method.setRequestHeader("X-Request", "JSON"); //$NON-NLS-1$ //$NON-NLS-2$ if (method != null) { int statusCode = -1; try { statusCode = client.executeMethod(method); if (statusCode == 200) { String responseContent = new String(method.getResponseBody()); return responseContent; } else if (statusCode == 500) { String val = params.remove(NAME); params.put(NAME, val + new Random().nextInt()); return executeAddApiKey(url, params, cookies); } } catch (IOException e) { throw new SdkException(e); } finally { method.releaseConnection(); } } return null; }