List of usage examples for org.apache.commons.httpclient HttpMethod setQueryString
public abstract void setQueryString(NameValuePair[] paramArrayOfNameValuePair);
From source file:org.abstracthorizon.proximity.storage.remote.CommonsHttpClientRemotePeer.java
/** * Execute method.//from w w w . j a va2 s . c om * * @param method the method * * @return the int */ protected int executeMethod(HttpMethod method) { if (getUserAgentString() != null) { method.setRequestHeader(new Header("user-agent", getUserAgentString())); } method.setRequestHeader(new Header("accept", "*/*")); method.setRequestHeader(new Header("accept-language", "en-us")); method.setRequestHeader(new Header("accept-encoding", "gzip, identity")); method.setRequestHeader(new Header("connection", "Keep-Alive")); method.setRequestHeader(new Header("cache-control", "no-cache")); // TODO: fix for #93 // method.setFollowRedirects(isFollowRedirection()); method.setFollowRedirects(true); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, httpRetryHandler); method.setQueryString(getQueryString()); int resultCode = 0; try { resultCode = getHttpClient().executeMethod(httpConfiguration, method); } catch (HttpException ex) { logger.error("Protocol error while executing " + method.getName() + " method", ex); } catch (IOException ex) { logger.error("Tranport error while executing " + method.getName() + " method", ex); } return resultCode; }
From source file:org.agnitas.dao.impl.VersionControlDaoImpl.java
private String fetchServerVersion(String currentVersion, String referrer) { HttpClient client = new HttpClient(); client.setConnectionTimeout(CONNECTION_TIMEOUT); HttpMethod method = new GetMethod(URL); method.setRequestHeader("referer", referrer); NameValuePair[] queryParams = new NameValuePair[1]; queryParams[0] = new NameValuePair(VERSION_KEY, currentVersion); method.setQueryString(queryParams); method.setFollowRedirects(true);//from w w w. j a va2 s. c om String responseBody = null; try { client.executeMethod(method); responseBody = method.getResponseBodyAsString(); } catch (Exception he) { logger.error("HTTP error connecting to '" + URL + "'", he); } //clean up the connection resources method.releaseConnection(); return responseBody; }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
public void abort(Transfer transfer) throws TransferException { TransferTarget target = transfer.getTransferTarget(); HttpMethod abortRequest = getPostMethod(); try {/*from w w w.j av a 2 s . c o m*/ HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); abortRequest.setPath(target.getEndpointPath() + "/abort"); //Put the transferId on the query string abortRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); try { int responseStatus = httpClient.executeMethod(hostConfig, abortRequest, httpState); checkResponseStatus("abort", responseStatus, abortRequest); //If we get here then we've received a 200 response //We're expecting the transfer id encoded in a JSON object... } catch (RuntimeException e) { throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.debug(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "abort", target.toString(), e.toString() }, e); } } finally { abortRequest.releaseConnection(); } }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
public void commit(Transfer transfer) throws TransferException { TransferTarget target = transfer.getTransferTarget(); HttpMethod commitRequest = getPostMethod(); try {//from w w w . j a v a2s . c o m HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); commitRequest.setPath(target.getEndpointPath() + "/commit"); //Put the transferId on the query string commitRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); try { int responseStatus = httpClient.executeMethod(hostConfig, commitRequest, httpState); checkResponseStatus("commit", responseStatus, commitRequest); //If we get here then we've received a 200 response //We're expecting the transfer id encoded in a JSON object... } catch (RuntimeException e) { throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.error(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "commit", target.toString(), e.toString() }, e); } } finally { commitRequest.releaseConnection(); } }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
public void prepare(Transfer transfer) throws TransferException { TransferTarget target = transfer.getTransferTarget(); HttpMethod prepareRequest = getPostMethod(); try {//from w w w . ja va2 s. c o m HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); prepareRequest.setPath(target.getEndpointPath() + "/prepare"); //Put the transferId on the query string prepareRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); try { int responseStatus = httpClient.executeMethod(hostConfig, prepareRequest, httpState); checkResponseStatus("prepare", responseStatus, prepareRequest); //If we get here then we've received a 200 response //We're expecting the transfer id encoded in a JSON object... } catch (RuntimeException e) { throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.debug(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "prepare", target.toString(), e.toString() }, e); } } finally { prepareRequest.releaseConnection(); } }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
/** * *//*from www . j av a 2s . co m*/ public TransferProgress getStatus(Transfer transfer) throws TransferException { TransferTarget target = transfer.getTransferTarget(); HttpMethod statusRequest = getPostMethod(); try { HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); statusRequest.setPath(target.getEndpointPath() + "/status"); //Put the transferId on the query string statusRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); try { int responseStatus = httpClient.executeMethod(hostConfig, statusRequest, httpState); checkResponseStatus("status", responseStatus, statusRequest); //If we get here then we've received a 200 response String statusPayload = statusRequest.getResponseBodyAsString(); JSONObject statusObj = new JSONObject(statusPayload); //We're expecting the transfer progress encoded in a JSON object... int currentPosition = statusObj.getInt("currentPosition"); int endPosition = statusObj.getInt("endPosition"); String statusStr = statusObj.getString("status"); TransferProgress p = new TransferProgress(); if (statusObj.has("error")) { JSONObject errorJSON = statusObj.getJSONObject("error"); Throwable throwable = rehydrateError(errorJSON); p.setError(throwable); } p.setStatus(TransferProgress.Status.valueOf(statusStr)); p.setCurrentPosition(currentPosition); p.setEndPosition(endPosition); return p; } catch (RuntimeException e) { throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.debug(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "status", target.toString(), e.toString() }, e); } } finally { statusRequest.releaseConnection(); } }
From source file:org.apache.camel.component.http.HttpProducer.java
/** * Creates the HttpMethod to use to call the remote server, either its GET or POST. * * @param exchange the exchange// w w w . ja v a 2s .c o m * @return the created method as either GET or POST * @throws CamelExchangeException is thrown if error creating RequestEntity */ @SuppressWarnings("deprecation") protected HttpMethod createMethod(Exchange exchange) throws Exception { // creating the url to use takes 2-steps String url = HttpHelper.createURL(exchange, getEndpoint()); URI uri = HttpHelper.createURI(exchange, url, getEndpoint()); // get the url and query string from the uri url = uri.toASCIIString(); String queryString = uri.getRawQuery(); // execute any custom url rewrite String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this); if (rewriteUrl != null) { // update url and query string from the rewritten url url = rewriteUrl; uri = new URI(url); // use raw query to have uri decimal encoded which http client requires queryString = uri.getRawQuery(); } // remove query string as http client does not accept that if (url.indexOf('?') != -1) { url = url.substring(0, url.indexOf('?')); } // create http holder objects for the request RequestEntity requestEntity = createRequestEntity(exchange); HttpMethods methodToUse = HttpHelper.createMethod(exchange, getEndpoint(), requestEntity != null); HttpMethod method = methodToUse.createMethod(url); if (queryString != null) { // need to encode query string queryString = UnsafeUriCharactersEncoder.encode(queryString); method.setQueryString(queryString); } LOG.trace("Using URL: {} with method: {}", url, method); if (methodToUse.isEntityEnclosing()) { ((EntityEnclosingMethod) method).setRequestEntity(requestEntity); if (requestEntity != null && requestEntity.getContentType() == null) { LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange); } } // there must be a host on the method if (method.getHostConfiguration().getHost() == null) { throw new IllegalArgumentException("Invalid uri: " + url + ". If you are forwarding/bridging http endpoints, then enable the bridgeEndpoint option on the endpoint: " + getEndpoint()); } return method; }
From source file:org.apache.cocoon.generation.WebServiceProxyGenerator.java
/** * Forwards the request and returns the response. * /*from www .j a v a2s . com*/ * The rest is probably out of date: * Will use a UrlGetMethod to benefit the cacheing mechanism * and intermediate proxy servers. * It is potentially possible that the size of the request * may grow beyond a certain limit for GET and it will require POST instead. * * @return byte[] XML response */ public byte[] fetch() throws ProcessingException { HttpMethod method = null; // check which method (GET or POST) to use. if (this.configuredHttpMethod.equalsIgnoreCase(METHOD_POST)) { method = new PostMethod(this.source); } else { method = new GetMethod(this.source); } if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("request HTTP method: " + method.getName()); } // this should probably be exposed as a sitemap option method.setFollowRedirects(true); // copy request parameters and merge with URL parameters Request request = ObjectModelHelper.getRequest(objectModel); ArrayList paramList = new ArrayList(); Enumeration enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String pname = (String) enumeration.nextElement(); String[] paramsForName = request.getParameterValues(pname); for (int i = 0; i < paramsForName.length; i++) { NameValuePair pair = new NameValuePair(pname, paramsForName[i]); paramList.add(pair); } } if (paramList.size() > 0) { NameValuePair[] allSubmitParams = new NameValuePair[paramList.size()]; paramList.toArray(allSubmitParams); String urlQryString = method.getQueryString(); // use HttpClient encoding routines method.setQueryString(allSubmitParams); String submitQryString = method.getQueryString(); // set final web service query string // sometimes the querystring is null here... if (null == urlQryString) { method.setQueryString(submitQryString); } else { method.setQueryString(urlQryString + "&" + submitQryString); } } // if there are submit parameters byte[] response = null; try { int httpStatus = httpClient.executeMethod(method); if (httpStatus < 400) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("Return code when accessing the remote Url: " + httpStatus); } } else { throw new ProcessingException("The remote returned error " + httpStatus + " when attempting to access remote URL:" + method.getURI()); } } catch (URIException e) { throw new ProcessingException("There is a problem with the URI: " + this.source, e); } catch (IOException e) { try { throw new ProcessingException( "Exception when attempting to access the remote URL: " + method.getURI(), e); } catch (URIException ue) { throw new ProcessingException("There is a problem with the URI: " + this.source, ue); } } finally { /* It is important to always read the entire response and release the * connection regardless of whether the server returned an error or not. * {@link http://jakarta.apache.org/commons/httpclient/tutorial.html} */ response = method.getResponseBody(); method.releaseConnection(); } return response; }
From source file:org.apache.cocoon.transformation.SparqlTransformer.java
private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters) throws ProcessingException, IOException, SAXException { HttpClient httpclient = new HttpClient(); if (System.getProperty("http.proxyHost") != null) { // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost")); String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", ""); if (nonProxyHostsRE.length() > 0) { String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|"); nonProxyHostsRE = ""; for (String pHost : pHosts) { nonProxyHostsRE += "|(^https?://" + pHost + ".*$)"; }/*from w w w . ja va 2s . c o m*/ nonProxyHostsRE = nonProxyHostsRE.substring(1); } if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) { try { HostConfiguration hostConfiguration = httpclient.getHostConfiguration(); hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort", "80"))); httpclient.setHostConfiguration(hostConfiguration); } catch (Exception e) { throw new ProcessingException("Cannot set proxy!", e); } } } // Make the HttpMethod. HttpMethod httpMethod = null; // Do not use empty query parameter. if (requestParameters.getParameter(parameterName).trim().equals("")) { requestParameters.removeParameter(parameterName); } // Instantiate different HTTP methods. if ("GET".equalsIgnoreCase(method)) { httpMethod = new GetMethod(url); if (requestParameters.getEncodedQueryString() != null) { httpMethod.setQueryString( requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */ } else { httpMethod.setQueryString(""); } } else if ("POST".equalsIgnoreCase(method)) { PostMethod httpPostMethod = new PostMethod(url); if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE)) .startsWith("application/x-www-form-urlencoded")) { // Encode parameters in POST body. Iterator parNames = requestParameters.getParameterNames(); while (parNames.hasNext()) { String parName = (String) parNames.next(); httpPostMethod.addParameter(parName, requestParameters.getParameter(parName)); } } else { // Use query parameter as POST body httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName)); // Add other parameters to query string requestParameters.removeParameter(parameterName); if (requestParameters.getEncodedQueryString() != null) { httpPostMethod.setQueryString( requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */ } else { httpPostMethod.setQueryString(""); } } httpMethod = httpPostMethod; } else if ("PUT".equalsIgnoreCase(method)) { PutMethod httpPutMethod = new PutMethod(url); httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName)); requestParameters.removeParameter(parameterName); httpPutMethod.setQueryString(requestParameters.getEncodedQueryString()); httpMethod = httpPutMethod; } else if ("DELETE".equalsIgnoreCase(method)) { httpMethod = new DeleteMethod(url); httpMethod.setQueryString(requestParameters.getEncodedQueryString()); } else { throw new ProcessingException("Unsupported method: " + method); } // Authentication (optional). if (credentials != null && credentials.length() > 0) { String[] unpw = credentials.split("\t"); httpclient.getParams().setAuthenticationPreemptive(true); httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(), httpMethod.getURI().getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(unpw[0], unpw[1])); } // Add request headers. Iterator headers = httpHeaders.entrySet().iterator(); while (headers.hasNext()) { Map.Entry header = (Map.Entry) headers.next(); httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue()); } // Declare some variables before the try-block. XMLizer xmlizer = null; try { // Execute the request. int responseCode; responseCode = httpclient.executeMethod(httpMethod); // Handle errors, if any. if (responseCode < 200 || responseCode >= 300) { if (showErrors) { AttributesImpl attrs = new AttributesImpl(); attrs.addCDATAAttribute("status", "" + responseCode); xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs); String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString(); xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error"); return; // Not a nice, but quick and dirty way to end. } else { throw new ProcessingException("Received HTTP status code " + responseCode + " " + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString()); } } // Parse the response if (responseCode == 204) { // No content. String statusLine = httpMethod.getStatusLine().toString(); xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES); xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result"); } else if (parse.equalsIgnoreCase("xml")) { InputStream responseBodyStream = httpMethod.getResponseBodyAsStream(); xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE); xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(), new IncludeXMLConsumer(xmlConsumer)); responseBodyStream.close(); } else if (parse.equalsIgnoreCase("text")) { xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES); String responseBody = httpMethod.getResponseBodyAsString(); xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result"); } else { throw new ProcessingException("Unknown parse type: " + parse); } } catch (ServiceException e) { throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e); } finally { if (xmlizer != null) manager.release((Component) xmlizer); httpMethod.releaseConnection(); } }
From source file:org.apache.hcatalog.templeton.TestWebHCatE2e.java
/** * Does a basic HTTP GET and returns Http Status code + response body * Will add the dummy user query string/*from w w w . j a v a2 s. co m*/ */ private static MethodCallRetVal doHttpCall(String uri, HTTP_METHOD_TYPE type, Map<String, Object> data, NameValuePair[] params) throws IOException { HttpClient client = new HttpClient(); HttpMethod method; switch (type) { case GET: method = new GetMethod(uri); break; case DELETE: method = new DeleteMethod(uri); break; case PUT: method = new PutMethod(uri); if (data == null) { break; } String msgBody = JsonBuilder.mapToJson(data); LOG.info("Msg Body: " + msgBody); StringRequestEntity sre = new StringRequestEntity(msgBody, "application/json", charSet); ((PutMethod) method).setRequestEntity(sre); break; default: throw new IllegalArgumentException("Unsupported method type: " + type); } if (params == null) { method.setQueryString(new NameValuePair[] { new NameValuePair("user.name", username) }); } else { NameValuePair[] newParams = new NameValuePair[params.length + 1]; System.arraycopy(params, 0, newParams, 1, params.length); newParams[0] = new NameValuePair("user.name", username); method.setQueryString(newParams); } String actualUri = "no URI"; try { actualUri = method.getURI().toString();//should this be escaped string? LOG.debug(type + ": " + method.getURI().getEscapedURI()); int httpStatus = client.executeMethod(method); LOG.debug("Http Status Code=" + httpStatus); String resp = method.getResponseBodyAsString(); LOG.debug("response: " + resp); return new MethodCallRetVal(httpStatus, resp, actualUri, method.getName()); } catch (IOException ex) { LOG.error("doHttpCall() failed", ex); } finally { method.releaseConnection(); } return new MethodCallRetVal(-1, "Http " + type + " failed; see log file for details", actualUri, method.getName()); }