List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:org.apache.shindig.social.sample.service.SampleContainerHandler.java
private String fetchStateDocument(String stateFileLocation) { String errorMessage = "The json state file " + stateFileLocation + " could not be fetched and parsed."; HttpMethod jsonState = new GetMethod(stateFileLocation); HttpClient client = new HttpClient(); try {/*w w w. j a v a 2 s . co m*/ client.executeMethod(jsonState); if (jsonState.getStatusCode() != 200) { throw new RuntimeException(errorMessage); } return jsonState.getResponseBodyAsString(); } catch (IOException e) { throw new RuntimeException(errorMessage, e); } finally { jsonState.releaseConnection(); } }
From source file:org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.java
public NamedList<Object> request(final SolrRequest request, ResponseParser processor) throws SolrServerException, IOException { HttpMethod method = null; InputStream is = null;/*from w w w. ja v a2s . c o m*/ SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = "/select"; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = _parser; } // The parser 'wt=' and 'version=' params are used instead of the original params ModifiableSolrParams wparams = new ModifiableSolrParams(); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (params == null) { params = wparams; } else { params = new DefaultSolrParams(wparams, params); } if (_invariantParams != null) { params = new DefaultSolrParams(_invariantParams, params); } int tries = _maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = _baseURL + path; boolean isMultipart = (streams != null && streams.size() > 1); if (streams == null || isMultipart) { PostMethod post = new PostMethod(url); post.getParams().setContentCharset("UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (this.useMultiPartPost || isMultipart) { parts.add(new StringPart(p, v, "UTF-8")); } else { post.addParameter(p, v); } } } } if (isMultipart) { int i = 0; for (ContentStream content : streams) { final ContentStream c = content; String charSet = null; PartSource source = new PartSource() { public long getLength() { return c.getSize(); } public String getFileName() { return c.getName(); } public InputStream createInputStream() throws IOException { return c.getStream(); } }; parts.add(new FilePart(c.getName(), source, c.getContentType(), charSet)); } } if (parts.size() > 0) { post.setRequestEntity(new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), post.getParams())); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(params, false); PostMethod post = new PostMethod(url + pstr); // post.setRequestHeader("connection", "close"); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setRequestEntity(new RequestEntity() { public long getContentLength() { return -1; } public String getContentType() { return contentStream[0].getContentType(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream outputStream) throws IOException { ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream); } }); } else { is = contentStream[0].getStream(); post.setRequestEntity( new InputStreamRequestEntity(is, contentStream[0].getContentType())); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { // This is generally safe to retry on method.releaseConnection(); method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if ((tries < 1)) { throw r; } //log.warn( "Caught: " + r + ". Retrying..." ); } } } catch (IOException ex) { log.error("####request####", ex); throw new SolrServerException("error reading streams", ex); } method.setFollowRedirects(_followRedirects); method.addRequestHeader("User-Agent", AGENT); if (_allowCompression) { method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate")); } // method.setRequestHeader("connection", "close"); try { // Execute the method. //System.out.println( "EXECUTE:"+method.getURI() ); int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { StringBuilder msg = new StringBuilder(); msg.append(method.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append(method.getStatusText()); msg.append("\n\n"); msg.append("request: " + method.getURI()); throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8")); } // Read the contents String charset = "UTF-8"; if (method instanceof HttpMethodBase) { charset = ((HttpMethodBase) method).getResponseCharSet(); } InputStream respBody = method.getResponseBodyAsStream(); // Jakarta Commons HTTPClient doesn't handle any // compression natively. Handle gzip or deflate // here if applicable. if (_allowCompression) { Header contentEncodingHeader = method.getResponseHeader("Content-Encoding"); if (contentEncodingHeader != null) { String contentEncoding = contentEncodingHeader.getValue(); if (contentEncoding.contains("gzip")) { //log.debug( "wrapping response in GZIPInputStream" ); respBody = new GZIPInputStream(respBody); } else if (contentEncoding.contains("deflate")) { //log.debug( "wrapping response in InflaterInputStream" ); respBody = new InflaterInputStream(respBody); } } else { Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader.getValue(); if (contentType != null) { if (contentType.startsWith("application/x-gzip-compressed")) { //log.debug( "wrapping response in GZIPInputStream" ); respBody = new GZIPInputStream(respBody); } else if (contentType.startsWith("application/x-deflate")) { //log.debug( "wrapping response in InflaterInputStream" ); respBody = new InflaterInputStream(respBody); } } } } } return processor.processResponse(respBody, charset); } catch (HttpException e) { throw new SolrServerException(e); } catch (IOException e) { throw new SolrServerException(e); } finally { method.releaseConnection(); if (is != null) { is.close(); } } }
From source file:org.apache.tapestry5.cdi.test.InjectTest.java
/** * Connect to an url thanks to an HttpClient if provided and return the response content as a String * Use same HttpClient to keep same HttpSession through multiple getResponse method calls * @param url an url to connect to/*from w ww .jav a 2s.c o m*/ * @param client an HTTPClient to use to serve the url * @return the response as a String */ private String getResponse(URL url, HttpClient client) { HttpClient newClient = client == null ? new HttpClient() : client; HttpMethod get = new GetMethod(url.toString()); String output = null; int out = 200; try { out = newClient.executeMethod(get); if (out != 200) { throw new RuntimeException("get " + get.getURI() + " returned " + out); } output = get.getResponseBodyAsString(); } catch (HttpException e) { e.printStackTrace(); throw new RuntimeException("get " + url + " returned " + out); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("get " + url + " returned " + out); } finally { get.releaseConnection(); } return output; }
From source file:org.apache.wink.itest.addressbook.StringTest.java
public void clearDatabase() { /*// ww w .ja v a 2 s . c o m * clear the database entries */ HttpMethod method = null; try { method = new PostMethod(getBaseURI() + "/clear"); client.executeMethod(method); assertEquals(204, method.getStatusCode()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:org.apache.wink.itest.addressbook.StringTest.java
/** * This will drive a GET request with no input parameters */// ww w . j a v a 2 s. c o m public void testGetNoParams() { HttpMethod method = null; try { HttpClient client = new HttpClient(); method = new GetMethod(getBaseURI()); client.executeMethod(method); String responseBody = method.getResponseBodyAsString(); Address addr = AddressBook.defaultAddress; assertTrue(responseBody.contains(addr.getEntryName())); assertTrue(responseBody.contains(addr.getStreetAddress())); assertTrue(responseBody.contains(addr.getZipCode())); assertTrue(responseBody.contains(addr.getCity())); assertTrue(responseBody.contains(addr.getCountry())); assertTrue(responseBody.contains(addr.getState())); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:org.apache.wink.itest.addressbook.StringTest.java
/** * This will drive a POST request with parameters from the query string *///from ww w. ja v a 2s . c om public void testPostWithQueryParams() { HttpMethod method = null; HttpMethod getMethod = null; try { // make sure everything is clear before testing HttpClient client = new HttpClient(); method = new PostMethod(getBaseURI()); method.setQueryString("entryName=newAddress&streetAddress=1234+Any+Street&city=" + "AnyTown&zipCode=90210&state=TX&country=US"); client.executeMethod(method); // now let's see if the address we just created is available getMethod = new GetMethod(getBaseURI() + "/newAddress"); client.executeMethod(getMethod); assertEquals(200, getMethod.getStatusCode()); String responseBody = getMethod.getResponseBodyAsString(); assertNotNull(responseBody); assertTrue(responseBody, responseBody.contains("newAddress")); assertTrue(responseBody, responseBody.contains("1234 Any Street")); assertTrue(responseBody, responseBody.contains("AnyTown")); assertTrue(responseBody, responseBody.contains("90210")); assertTrue(responseBody, responseBody.contains("TX")); assertTrue(responseBody, responseBody.contains("US")); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (method != null) { method.releaseConnection(); } if (getMethod != null) { getMethod.releaseConnection(); } } }
From source file:org.apache.wink.itest.cachetest.ClientTest.java
@Override public void setUp() { /*/*from w w w. j a v a 2s.com*/ * clear the database entries */ HttpClient client = new HttpClient(); HttpMethod method = null; try { System.out.println(NEWS_BASE_URI + "/clear"); method = new PostMethod(NEWS_BASE_URI + "/clear"); client.executeMethod(method); assertEquals(204, method.getStatusCode()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:org.apache.wink.itest.MatrixParamTest.java
protected String sendGoodRequestAndGetResponse(String aPartialRequestURL, Class<? extends HttpMethod> aClass) { try {// w w w.j av a2 s . c o m HttpMethod httpMethod = aClass.newInstance(); httpMethod.setURI(new URI(BASE_URI + aPartialRequestURL, false)); httpclient = new HttpClient(); try { int result = httpclient.executeMethod(httpMethod); System.out.println("Response status code: " + result); System.out.println("Response body: "); String responseBody = httpMethod.getResponseBodyAsString(); System.out.println(responseBody); assertEquals(result, 200); return responseBody; } catch (IOException ioe) { ioe.printStackTrace(); fail(ioe.getMessage()); } finally { httpMethod.releaseConnection(); } } catch (URIException e) { e.printStackTrace(); fail(e.getMessage()); } catch (IllegalAccessException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InstantiationException e) { e.printStackTrace(); fail(e.getMessage()); } return null; }
From source file:org.apache.wink.itest.nofindmethods.DoNotUseMethodNamesForHTTPVerbsTest.java
/** * Negative tests that method names that begin with HTTP verbs are not * invoked on a root resource./*from w ww. j a v a 2 s .c o m*/ * * @throws HttpException * @throws IOException */ public void testMethodsNotValid() throws HttpException, IOException { HttpMethod method = new PostMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/someresource"); try { client.executeMethod(method); assertEquals(405, method.getStatusCode()); } finally { method.releaseConnection(); } method = new GetMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/someresource"); try { client.executeMethod(method); assertEquals(405, method.getStatusCode()); } finally { method.releaseConnection(); } method = new PutMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/someresource"); try { client.executeMethod(method); assertEquals(405, method.getStatusCode()); } finally { method.releaseConnection(); } method = new DeleteMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/someresource"); try { client.executeMethod(method); assertEquals(405, method.getStatusCode()); } finally { method.releaseConnection(); } method = new GetMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/counter/root"); try { client.executeMethod(method); assertEquals(200, method.getStatusCode()); assertEquals("0", method.getResponseBodyAsString()); } finally { method.releaseConnection(); } }
From source file:org.apache.wink.itest.nofindmethods.DoNotUseMethodNamesForHTTPVerbsTest.java
/** * Negative tests that method names that begin with HTTP verbs are not * invoked on a sublocator method.//from www.jav a 2s. co m * * @throws HttpException * @throws IOException */ public void testSublocatorMethodsNotValid() throws HttpException, IOException { HttpMethod method = new PostMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/sublocatorresource/sub"); try { client.executeMethod(method); assertEquals(405, method.getStatusCode()); } finally { method.releaseConnection(); } method = new GetMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/sublocatorresource/sub"); try { client.executeMethod(method); assertEquals(405, method.getStatusCode()); } finally { method.releaseConnection(); } method = new PutMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/sublocatorresource/sub"); try { client.executeMethod(method); assertEquals(405, method.getStatusCode()); } finally { method.releaseConnection(); } method = new DeleteMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/sublocatorresource/sub"); try { client.executeMethod(method); assertEquals(405, method.getStatusCode()); } finally { method.releaseConnection(); } method = new GetMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/counter/sublocator"); try { client.executeMethod(method); assertEquals(200, method.getStatusCode()); assertEquals("0", method.getResponseBodyAsString()); } finally { method.releaseConnection(); } }