Package org.apache.commons.httpclient.methods

Examples of org.apache.commons.httpclient.methods.EntityEnclosingMethod


      for (String headerValue : entry.getValue()) {
        httpMethod.addRequestHeader(headerName, headerValue);
      }
    }
    if (this.httpMethod instanceof EntityEnclosingMethod) {
      EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) this.httpMethod;
      RequestEntity requestEntity = new ByteArrayRequestEntity(output);
      entityEnclosingMethod.setRequestEntity(requestEntity);
    }
    this.httpClient.executeMethod(this.httpMethod);
    return new CommonsClientHttpResponse(this.httpMethod);
  }
View Full Code Here


                webRequestSettings.getRequestParameters().toArray(pairs);
                httpMethod.setQueryString(NameValuePair.toHttpClient(pairs));
            }
        }
        else { // POST as well as PUT
            final EntityEnclosingMethod method = (EntityEnclosingMethod) httpMethod;
            method.getParams().setContentCharset(webRequestSettings.getCharset());

            final String queryString = url.getQuery();
            method.setQueryString(queryString);
            if (webRequestSettings.getRequestBody() != null) {
                final String body = webRequestSettings.getRequestBody();
                final String charset = webRequestSettings.getCharset();
                method.setRequestEntity(new StringRequestEntity(body, null, charset));
            }

            // Note that this has to be done in two loops otherwise it won't
            // be able to support two elements with the same name.
            if (webRequestSettings.getEncodingType() == FormEncodingType.URL_ENCODED
                    && method instanceof PostMethod) {
                final PostMethod postMethod = (PostMethod) httpMethod;
                for (final NameValuePair pair : webRequestSettings.getRequestParameters()) {
                    postMethod.removeParameter(pair.getName(), pair.getValue());
                }

                for (final NameValuePair pair : webRequestSettings.getRequestParameters()) {
                    postMethod.addParameter(pair.getName(), pair.getValue());
                }
            }
            else if (FormEncodingType.MULTIPART == webRequestSettings.getEncodingType()) {
                final List<PartBase> partList = new ArrayList<PartBase>();
                for (final NameValuePair pair : webRequestSettings.getRequestParameters()) {
                    final PartBase newPart;
                    if (pair instanceof KeyDataPair) {
                        final KeyDataPair pairWithFile = (KeyDataPair) pair;
                        final String charset = webRequestSettings.getCharset();
                        newPart = buildFilePart(pairWithFile, charset);
                    }
                    else {
                        newPart = new StringPart(pair.getName(), pair.getValue(), webRequestSettings.getCharset());
                        newPart.setContentType(null); // Firefox and IE seem not to send a content type
                    }
                    newPart.setTransferEncoding(null); // Firefox and IE don't send transfer encoding headers
                    partList.add(newPart);
                }
                Part[] parts = new Part[partList.size()];
                parts = partList.toArray(parts);
                method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
            }
            else { // for instance a PUT request
                final String body = webRequestSettings.getRequestBody();
                if (body != null) {
                    final String contentType = webRequestSettings.getAdditionalHeaders().get("Content-type");
                    final String charset = webRequestSettings.getCharset();
                    method.setRequestEntity(new StringRequestEntity(body, contentType, charset));
                }
            }
        }

        httpMethod.setRequestHeader("User-Agent", webClient_.getBrowserVersion().getUserAgent());
View Full Code Here

   public void testRestPutEmbeddedHotRodGet() throws Exception {
      final String key = "1";

      // 1. Put with REST
      EntityEnclosingMethod put = new PutMethod(cacheFactory.getRestUrl() + "/" + key);
      put.setRequestEntity(new ByteArrayRequestEntity(
            "<hey>ho</hey>".getBytes(), "application/octet-stream"));
      HttpClient restClient = cacheFactory.getRestClient();
      restClient.executeMethod(put);
      assertEquals(HttpServletResponse.SC_OK, put.getStatusCode());
      assertEquals("", put.getResponseBodyAsString().trim());

      // 2. Get with Embedded
      assertArrayEquals("<hey>ho</hey>".getBytes(), (byte[])
            cacheFactory.getEmbeddedCache().get(key));
View Full Code Here

      assertTrue(l.created.isEmpty());
      assertTrue(l.removed.isEmpty());
      assertTrue(l.modified.isEmpty());
      assertTrue(l.visited.isEmpty());

      EntityEnclosingMethod put = new PutMethod(restUrl + "/k");
      put.setRequestEntity(new ByteArrayRequestEntity(
            "v".getBytes(), "application/octet-stream"));
      remote.executeMethod(put);

      assertEquals(1, l.createdCounter);
      assertEquals("v".getBytes(), (byte[]) l.created.get("k"));
      assertTrue(l.removed.isEmpty());
      assertEquals(0, l.modifiedCounter);
      assertTrue(l.visited.isEmpty());


      EntityEnclosingMethod put2 = new PutMethod(restUrl + "/key");
      put2.setRequestEntity(new ByteArrayRequestEntity(
            "value".getBytes(), "application/octet-stream"));
      remote.executeMethod(put2);

      assertEquals(2, l.createdCounter);
      assertTrue(l.removed.isEmpty());
      assertEquals(0, l.modifiedCounter);
      assertTrue(l.visited.isEmpty());

      EntityEnclosingMethod put3 = new PutMethod(restUrl + "/key");
      put3.setRequestEntity(new ByteArrayRequestEntity(
            "modifiedValue".getBytes(), "application/octet-stream"));
      remote.executeMethod(put3);

      assertEquals(2, l.createdCounter);
      assertTrue(l.removed.isEmpty());
      assertEquals(1, l.modifiedCounter);
      assertEquals("modifiedValue".getBytes(), (byte[]) l.modified.get("key"));
      assertTrue(l.visited.isEmpty());

      EntityEnclosingMethod post = new PutMethod(restUrl + "/k");
      post.setRequestEntity(new ByteArrayRequestEntity(
            "replacedValue".getBytes(), "application/octet-stream"));
      remote.executeMethod(post);

      assertEquals(2, l.createdCounter);
      assertTrue(l.removed.isEmpty());
View Full Code Here

   public void testRestPutEmbeddedHotRodGet() throws Exception {
      final String key = "1";

      // 1. Put with REST
      EntityEnclosingMethod put = new PutMethod(cacheFactory1.getRestUrl() + "/" + key);
      put.setRequestEntity(new ByteArrayRequestEntity(
            "<hey>ho</hey>".getBytes(), "application/octet-stream"));
      HttpClient restClient = cacheFactory1.getRestClient();
      restClient.executeMethod(put);
      assertEquals(HttpServletResponse.SC_OK, put.getStatusCode());
      assertEquals("", put.getResponseBodyAsString().trim());

      // 2. Get with Embedded
      assertArrayEquals("<hey>ho</hey>".getBytes(), (byte[])
            cacheFactory2.getEmbeddedCache().get(key));
View Full Code Here

   public void testRestPutEmbeddedMemcachedHotRodGetTest() throws Exception {
      final String key = "3";

      // 1. Put with REST
      EntityEnclosingMethod put = new PutMethod(cacheFactory.getRestUrl() + "/" + key);
      put.setRequestEntity(new ByteArrayRequestEntity(
            "<hey>ho</hey>".getBytes(), "application/octet-stream"));
      HttpClient restClient = cacheFactory.getRestClient();
      restClient.executeMethod(put);
      assertEquals(HttpServletResponse.SC_OK, put.getStatusCode());
      assertEquals("", put.getResponseBodyAsString().trim());

      // 2. Get with Embedded (given a marshaller, it can unmarshall the result)
      assertEquals("<hey>ho</hey>",
            cacheFactory.getEmbeddedCache().get(key));
View Full Code Here

    */
   static private void
   uploadFileWork(String url, boolean isPost, File file, String contentType,
                  String cookie, ProgressListener listener)
   throws Exception {
      EntityEnclosingMethod method;
      final RequestEntity entity =
         new ProgressListenerRequestEntity(file, contentType, listener);
      if (isPost) {
         method = new PostMethod(url);
         method.setContentChunked(true);
      } else {
         method = new PutMethod(url);
         method.addRequestHeader("Cookie", cookie);
         method.setContentChunked(false);
         HttpMethodParams params = new HttpMethodParams();
         params.setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
         method.setParams(params);
      }
      method.setRequestEntity(entity);

      logger.info("upload " + file + " to " + url);
      long t1 = System.currentTimeMillis();
      boolean ok = false;
      try {
         HttpClient httpClient = new HttpClient();
         int statusCode = httpClient.executeMethod(method);
         String response = method.getResponseBodyAsString(100);
         logger.debug("status: " + statusCode + " response: " + response);
         if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) {
            throw new Exception("Http post failed");
         }
         method.releaseConnection();
         ok = true;
      } finally {
         if (!ok) {
            method.abort();
         }
      }
      long t2 = System.currentTimeMillis();
      logger.info("upload " + file + " done in " + (t2 - t1) + " ms");
   }
View Full Code Here

      }
      if (request.getBody() != null)
      {
         if (httpMethod instanceof GetMethod) throw new RuntimeException("A GET request cannot have a body.");
         ClientRequestEntity requestEntity = new ClientRequestEntity(new HttpClientHeaderWrapper(httpMethod, request.getProviderFactory()), request);
         EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod;
         post.setRequestEntity(requestEntity);
      }
   }
View Full Code Here

            // CONTENT_LENGTH_AUTO causes the EntityEnclosingMethod to buffer the whole input stream in memory so that the method can be
            // re-sent. For things like redirects this is nice. For authentication, it's necessary.
            requestStreamLength = InputStreamRequestEntity.CONTENT_LENGTH_AUTO;
        }
        stream.reset();
        EntityEnclosingMethod method = getMyEntityEnclosingMethod();
        if (contentType.length() > 0) {
            method.setRequestEntity(new InputStreamRequestEntity(stream, requestStreamLength, contentType));
        }
        else {
            method.setRequestEntity(new InputStreamRequestEntity(stream, requestStreamLength));
        }
        // there's an HttpClient 3.0.1 bug setting Expect headers. See ExpectContinueMethod.addRequestHeaders. That method discards
        // all Expect headers if USE_EXPECT_CONTINUE is false on the parameters, so we'll have to send Expect:100-continue whenever we
        // send any other expect headers. Note that this has the virtuous side-effect of preserving the Expect: 100-continue header passed
        // into the ScspClient.
        HttpMethodParams params = method.getParams();
        params.setParameter(HttpClientParams.USE_EXPECT_CONTINUE, useExpectContinue);
        //params.setExpectContinueTimeout(30000);

        HttpMethod resMethod = addHeadersToMethod(method);
        if (this.streamLength > 32768) {
View Full Code Here

        if (readTimeout != null) {
            methodParams.setSoTimeout(readTimeout);
        }

        if (method instanceof EntityEnclosingMethod) {
            final EntityEnclosingMethod entMethod = (EntityEnclosingMethod) method;

            if (cr.getEntity() != null) {
                final RequestEntityWriter re = getRequestEntityWriter(cr);
                final Integer chunkedEncodingSize = (Integer) props.get(ApacheHttpClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE);
                if (chunkedEncodingSize != null) {
                    // There doesn't seems to be a way to set the chunk size.
                    entMethod.setContentChunked(true);

                    // It is not possible for a MessageBodyWriter to modify
                    // the set of headers before writing out any bytes to
                    // the OutputStream
                    // This makes it impossible to use the multipart
                    // writer that modifies the content type to add a boundary
                    // parameter
                    writeOutBoundHeaders(cr.getHeaders(), method);

                    // Do not buffer the request entity when chunked encoding is
                    // set
                    entMethod.setRequestEntity(new RequestEntity() {

                        @Override
                        public boolean isRepeatable() {
                            return false;
                        }

                        @Override
                        public void writeRequest(OutputStream out) throws IOException {
                            re.writeRequestEntity(out);
                        }

                        @Override
                        public long getContentLength() {
                            return re.getSize();
                        }

                        @Override
                        public String getContentType() {
                            return re.getMediaType().toString();
                        }
                    });

                } else {
                    entMethod.setContentChunked(false);

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    try {
                        re.writeRequestEntity(new CommittingOutputStream(baos) {

                            @Override
                            protected void commit() throws IOException {
                                writeOutBoundHeaders(cr.getMetadata(), method);
                            }
                        });
                    } catch (IOException ex) {
                        throw new ClientHandlerException(ex);
                    }

                    final byte[] content = baos.toByteArray();
                    entMethod.setRequestEntity(new RequestEntity() {

                        @Override
                        public boolean isRepeatable() {
                            return true;
                        }
View Full Code Here

TOP

Related Classes of org.apache.commons.httpclient.methods.EntityEnclosingMethod

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.