List of usage examples for org.apache.commons.httpclient.methods PostMethod addParameter
public void addParameter(String paramString1, String paramString2) throws IllegalArgumentException
From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostResponseCreatorTest.java
public void testCustomPostResponseCreator() throws Exception { final PostMethod post = new PostMethod(postUrl + SlingPostConstants.DEFAULT_CREATE_SUFFIX); post.addParameter(":responseType", "custom"); post.setFollowRedirects(false);/*from ww w. j ava2 s . com*/ final int status = httpClient.executeMethod(post); assertEquals("Unexpected status response", 201, status); assertEquals("Thanks!", post.getResponseBodyAsString()); post.releaseConnection(); }
From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletNopTest.java
private void post(String url, String code, int expectedStatus) throws IOException { final PostMethod post = new PostMethod(url); post.setFollowRedirects(false);// w ww .j av a 2 s .c om post.addParameter(":operation", "nop"); if (code != null) { post.addParameter(":nopstatus", code); } int actualStatus = httpClient.executeMethod(post); assertEquals(expectedStatus, actualStatus); }
From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletOutputContentTypeTest.java
private void runTest(String acceptHeaderValue, boolean useHttpEquiv, String expectedContentType) throws Exception { final String info = (useHttpEquiv ? "Using http-equiv parameter" : "Using Accept header") + ": "; final String url = HTTP_BASE_URL + MY_TEST_PATH; final PostMethod post = new PostMethod(url); post.setFollowRedirects(false);/*from www . ja v a 2 s. c om*/ if (acceptHeaderValue != null) { if (useHttpEquiv) { post.addParameter(":http-equiv-accept", acceptHeaderValue); } else { post.addRequestHeader("Accept", acceptHeaderValue); } } final int status = httpClient.executeMethod(post) / 100; assertEquals(info + "Expected status 20x for POST at " + url, 2, status); final Header h = post.getResponseHeader("Content-Type"); assertNotNull(info + "Expected Content-Type header", h); final String ct = h.getValue(); assertTrue(info + "Expected Content-Type '" + expectedContentType + "' for Accept header=" + acceptHeaderValue + " but got '" + ct + "'", ct.startsWith(expectedContentType)); }
From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostStatusTest.java
private void simplePost(String url, String statusParam, int expectStatus, String expectLocation) throws IOException { final PostMethod post = new PostMethod(url); post.setFollowRedirects(false);//from w w w. j a v a2 s . co m if (statusParam != null) { post.addParameter(SlingPostConstants.RP_STATUS, statusParam); } final int status = httpClient.executeMethod(post); assertEquals("Unexpected status response", expectStatus, status); if (expectLocation != null) { String location = post.getResponseHeader("Location").getValue(); assertNotNull("Expected location header", location); assertTrue(location.endsWith(expectLocation)); } post.releaseConnection(); }
From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostToRootTest.java
public void testSetRootProperty() throws Exception { String url = HTTP_BASE_URL; if (!url.endsWith("/")) { url += "/"; }/*from w w w . ja v a2 s .c o m*/ final PostMethod post = new PostMethod(url); final String name = getClass().getSimpleName(); final String value = getClass().getSimpleName() + System.currentTimeMillis(); post.addParameter(name, value); final int status = httpClient.executeMethod(post); assertEquals(200, status); final String json = getContent(url + ".json", CONTENT_TYPE_JSON); assertJavascript(value, json, "out.print(data." + name + ")"); }
From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java
protected void removeConfiguration(final HttpClient client, final String targetURL, String pid) throws MojoExecutionException { final String postUrl = targetURL + "/configMgr/" + pid; final PostMethod post = new PostMethod(postUrl); post.addParameter("apply", "true"); post.addParameter("delete", "true"); try {/* w ww. j av a 2 s. c o m*/ final int status = client.executeMethod(post); // we get a moved temporarily back from the configMgr plugin if (status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_OK) { getLog().debug("Configuration removed."); } else { getLog().error("Removing configuration failed, cause: " + HttpStatus.getStatusText(status)); } } catch (HttpException ex) { throw new MojoExecutionException( "Removing configuration at " + postUrl + " failed, cause: " + ex.getMessage(), ex); } catch (IOException ex) { throw new MojoExecutionException( "Removing configuration at " + postUrl + " failed, cause: " + ex.getMessage(), ex); } finally { post.releaseConnection(); } }
From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java
/** * Add a new configuration for the file system provider * @throws MojoExecutionException//from w w w.j ava2 s . c om */ protected void addConfiguration(final HttpClient client, final String targetURL, String dir, String path) throws MojoExecutionException { final String postUrl = targetURL + "/configMgr/" + FS_FACTORY; final PostMethod post = new PostMethod(postUrl); post.addParameter("apply", "true"); post.addParameter("factoryPid", FS_FACTORY); post.addParameter("pid", "[Temporary PID replaced by real PID upon save]"); post.addParameter("provider.file", dir); post.addParameter("provider.roots", path); post.addParameter("propertylist", "provider.roots,provider.file"); try { final int status = client.executeMethod(post); // we get a moved temporarily back from the configMgr plugin if (status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_OK) { getLog().info("Configuration created."); } else { getLog().error("Configuration failed, cause: " + HttpStatus.getStatusText(status)); } } catch (HttpException ex) { throw new MojoExecutionException("Configuration on " + postUrl + " failed, cause: " + ex.getMessage(), ex); } catch (IOException ex) { throw new MojoExecutionException("Configuration on " + postUrl + " failed, cause: " + ex.getMessage(), ex); } finally { post.releaseConnection(); } }
From source file:org.apache.sling.maven.bundlesupport.BundleUninstallMojo.java
protected void postToFelix(String targetURL, String symbolicName) throws MojoExecutionException { final PostMethod post = new PostMethod(targetURL + "/bundles/" + symbolicName); post.addParameter("action", "uninstall"); try {/*from w w w . ja va 2 s. c om*/ int status = getHttpClient().executeMethod(post); if (status == HttpStatus.SC_OK) { getLog().info("Bundle uninstalled"); } else { getLog().error("Uninstall failed, cause: " + HttpStatus.getStatusText(status)); } } catch (Exception ex) { throw new MojoExecutionException("Uninstall from " + targetURL + " failed, cause: " + ex.getMessage(), ex); } finally { post.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;/*from ww w . j ava 2 s .co m*/ InputStream is = null; 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.wookie.tests.functional.PropertiesControllerTest.java
@Test public void setPreferenceUsingPostParameters() throws Exception { try {/*ww w . ja v a2 s . c o m*/ String url = TEST_PROPERTIES_SERVICE_URL_VALID; //String url = TEST_PROPERTIES_SERVICE_URL_VALID; HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); post.addParameter("api_key", API_KEY_VALID); post.addParameter("widgetid", WIDGET_ID_VALID); post.addParameter("userid", "test"); post.addParameter("is_public", "false"); post.addParameter("shareddatakey", "propstest"); post.addParameter("propertyname", "testpost"); post.addParameter("propertyvalue", "pass"); client.executeMethod(post); int code = post.getStatusCode(); assertEquals(201, code); post.releaseConnection(); } catch (Exception e) { fail("POST failed"); } try { HttpClient client = new HttpClient(); GetMethod get = new GetMethod(TEST_PROPERTIES_SERVICE_URL_VALID); get.setQueryString("api_key=" + API_KEY_VALID + "&widgetid=" + WIDGET_ID_VALID + "&userid=test&shareddatakey=propstest&propertyname=testpost"); client.executeMethod(get); int code = get.getStatusCode(); assertEquals(200, code); String resp = get.getResponseBodyAsString(); assertEquals("pass", resp); get.releaseConnection(); } catch (Exception e) { fail("POST failed to set info correctly"); } }