List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:org.apache.clerezza.integrationtest.web.performance.Get404.java
@Override public void run() { try {//from w w w . j av a 2 s .c o m URL serverURL = new URL(testSubjectUriPrefix + "/foobar"); HttpClient client = new HttpClient(); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); HttpMethod method = new GetMethod(serverURL.toString()); method.setRequestHeader("Accept", "*/*"); method.setDoAuthentication(true); try { int responseCode = client.executeMethod(method); if (responseCode != HttpStatus.SC_NOT_FOUND) { throw new RuntimeException("Get404: unexpected " + "response code: " + responseCode); } } finally { method.releaseConnection(); } } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.apache.cloudstack.network.element.SspClient.java
private String executeMethod(HttpMethod method) { String apiCallPath = null;/*from ww w. j a v a2 s .co m*/ try { apiCallPath = method.getName() + " " + method.getURI().toString(); } catch (URIException e) { s_logger.error("method getURI failed", e); } String response = null; try { client.executeMethod(method); response = method.getResponseBodyAsString(); } catch (HttpException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } catch (IOException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } finally { method.releaseConnection(); } if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { if (!login()) { return null; } try { client.executeMethod(method); response = method.getResponseBodyAsString(); } catch (HttpException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } catch (IOException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } finally { method.releaseConnection(); } } s_logger.info("ssp api call:" + apiCallPath + " user=" + username + " status=" + method.getStatusLine()); if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod emethod = (EntityEnclosingMethod) method; RequestEntity reqEntity = emethod.getRequestEntity(); if (reqEntity instanceof StringRequestEntity) { StringRequestEntity strReqEntity = (StringRequestEntity) reqEntity; s_logger.debug("ssp api request body:" + strReqEntity.getContent()); } else { s_logger.debug("ssp api request body:" + emethod.getRequestEntity()); } } s_logger.debug("ssp api response body:" + response); return response; }
From source file:org.apache.cocoon.generation.WebServiceProxyGenerator.java
/** * Forwards the request and returns the response. * /*from w ww .java 2s. c om*/ * 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 .j a v a2 s. c om 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.commons.httpclient.demo.GetOtherUrlDate.java
public static void main(String[] args) { //GetOtherUrlDate getotherurldate = new GetOtherUrlDate(); HttpClient hc = new HttpClient(); ////from w ww .ja va 2 s. c o m //hc.getHostConfiguration().setProxy("90.0.12.21",808); HttpMethod hm = new GetMethod("http://www.sina.com.cn"); hm.addRequestHeader("Content-Type", "text/html;charset=utf-8"); // int statusCode = -1; byte[] result = null; try { statusCode = hc.executeMethod(hm); if (statusCode != HttpStatus.SC_OK) { // System.out.println("get failure!"); return; } if (hm.getResponseBody() != null) { // result = hm.getResponseBody(); //hm.getStatusLine()DDhttp } } catch (HttpException e1) { e1.printStackTrace(); } catch (java.io.IOException e2) { e2.printStackTrace(); } hm.releaseConnection(); String data = null; if (result != null) { try { //data = new String(result, "UTF-8"); // data = new String(result, "GB2312"); // } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } //System.out.println(data.substring(0, 500)); // int begin = data.indexOf("product"); // System.out.println("==============================="); System.out.println("product:" + begin); System.out.println("==============================="); if (begin > -1) { //1000 System.out.println(data.substring(begin, begin + 1000)); //System.out.println(Strings.convertHTML(data.substring(begin,begin + 1000))); } } }
From source file:org.apache.commons.httpclient.demo.MultiThreadedHttpDemo.java
public static void main(String[] args) { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpClient client = new HttpClient(connectionManager); ///* w ww. j a v a2 s .com*/ //client.getHostConfiguration().setProxy("90.0.12.21",808); //GETHTTPSURLhttphttps HttpMethod method = new GetMethod("http://java.sun.com"); //POST //HttpMethod method = new PostMethod("http://java.sun.com"); try { client.executeMethod(method); } catch (IOException ex) { } // System.out.println("==================================="); System.out.println(""); System.out.println(method.getStatusLine()); System.out.println("==================================="); // System.out.println("==================================="); System.out.println(":"); try { System.out.println(method.getResponseBodyAsString()); } catch (IOException ex1) { } System.out.println("==================================="); // method.releaseConnection(); }
From source file:org.apache.commons.httpclient.demo.SimpleClient.java
public static void main(String[] args) throws IOException { HttpClient client = new HttpClient(); ////www . j a v a 2s. c om client.getHostConfiguration().setProxy("90.0.12.21", 808); //GETHTTPSURLhttphttps HttpMethod method = new GetMethod("http://java.sun.com"); //POST //HttpMethod method = new PostMethod("http://java.sun.com"); client.executeMethod(method); // System.out.println("==================================="); System.out.println(""); System.out.println(method.getStatusLine()); System.out.println("==================================="); // System.out.println("==================================="); System.out.println(":"); System.out.println(method.getResponseBodyAsString()); System.out.println("==================================="); // method.releaseConnection(); }
From source file:org.apache.commons.httpclient.demo.SimpleHttpClient.java
public static void main(String[] args) throws IOException { HttpClient client = new HttpClient(); ////from www. ja v a2 s . co m //client.getHostConfiguration().setProxy("90.0.12.21",808); client.getHostConfiguration().setHost("www.imobile.com.cn", 80, "http"); HttpMethod method = getPostMethod(); //POST //HttpMethod method = getPostMethod(); //GET client.executeMethod(method); // System.out.println("==================================="); System.out.println(""); System.out.println(method.getStatusLine()); System.out.println("==================================="); // String response = new String(method.getResponseBodyAsString().getBytes("8859_1")); // System.out.println("==================================="); System.out.println(":"); System.out.println(response); System.out.println("==================================="); method.releaseConnection(); }
From source file:org.apache.cxf.aegis.jaxws.AegisJaxwsGetTest.java
@Test public void testGetEcho() throws Exception { HttpClient httpClient = createClient(); String url = "http://localhost:" + PORT + "/Echo/echo/echo/hello"; HttpMethod method = null; method = new GetMethod(url); int status = httpClient.executeMethod(method); assertEquals(HttpStatus.SC_OK, status); String result = method.getResponseBodyAsString(); assertTrue(result.contains("hello")); method.releaseConnection(); httpClient = createClient();/*w ww .j ava 2 s . c om*/ url = "http://localhost:" + PORT + "/Echo/echo/echo/hello?wsdl"; method = new GetMethod(url); status = httpClient.executeMethod(method); assertEquals(HttpStatus.SC_OK, status); Document doc = StaxUtils.read(method.getResponseBodyAsStream()); Map<String, String> ns = new HashMap<String, String>(); ns.put("xsd", "http://www.w3.org/2001/XMLSchema"); NodeList nl = XPathAssert.assertValid("//xsd:element[@name='firstHeader']", doc.getDocumentElement(), ns); assertEquals(1, nl.getLength()); }
From source file:org.apache.cxf.aegis.jaxws.AegisJaxwsGetTest.java
@Test public void testGetEchoSimple() throws Exception { HttpClient httpClient = createClient(); String url = "http://localhost:" + PORT + "/SimpleEcho/simpleEcho/string/hello"; HttpMethod method = null; method = new GetMethod(url); int status = httpClient.executeMethod(method); assertEquals(HttpStatus.SC_OK, status); String result = method.getResponseBodyAsString(); assertTrue(result.contains("hello")); method.releaseConnection(); }