Package org.apache.commons.httpclient.methods

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


        for (int i = 0; i < headers.length; i++) {
            Header h = headers[i];
            sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue());
        }
        if (m instanceof EntityEnclosingMethod) {
            EntityEnclosingMethod eem = (EntityEnclosingMethod) m;
            if (eem.getRequestEntity() != null) {
                sb.append("\nRequest Entity:");
                sb.append("\n\tContent-Type:").append(eem.getRequestEntity().getContentType());
                sb.append("\n\tContent-Length:").append(eem.getRequestEntity().getContentLength());
                if (eem.getRequestEntity() instanceof StringRequestEntity) {
                    StringRequestEntity sre = (StringRequestEntity) eem.getRequestEntity();
                    sb.append("\n\tContent-Charset:").append(sre.getCharset());
                    sb.append("\n\tRequest Entity:\n").append(sre.getContent());
                }
            }
        }
View Full Code Here


                    requestEntity = new StringRequestEntity(DOMUtils.getTextContent(partValue), contentType, contentCharset);
                }
            }

            // cast safely, PUT and POST are subclasses of EntityEnclosingMethod
            final EntityEnclosingMethod enclosingMethod = (EntityEnclosingMethod) method;
            enclosingMethod.setRequestEntity(requestEntity);
            enclosingMethod.setContentChunked(params.getBooleanParameter(Properties.PROP_HTTP_REQUEST_CHUNK, false));

        } else {
            // should not happen because of HttpBindingValidator, but never say never
            throw new IllegalArgumentException("Unsupported HTTP method: " + verb);
        }
View Full Code Here

  // select best matching method (get,post, post multpart (file))

    boolean isBinary = false;
    boolean doMultiPart=doUploadFile || http.multiPart;
    PostMethod post=null;
    EntityEnclosingMethod eem=null;
   
   
    if(http.method==METHOD_GET) {
      httpMethod=new GetMethod(url);
    }
    else if(http.method==METHOD_HEAD) {
        httpMethod=new HeadMethod(url);
    }
    else if(http.method==METHOD_DELETE) {
      isBinary=true;
        httpMethod=new DeleteMethod(url);
    }
    else if(http.method==METHOD_PUT) {
      isBinary=true;
        httpMethod=eem=new PutMethod(url);
       
    }
    else if(http.method==METHOD_TRACE) {
      isBinary=true;
        httpMethod=new TraceMethod(url);
    }
    else if(http.method==METHOD_OPTIONS) {
      isBinary=true;
        httpMethod=new OptionsMethod(url);
    }
    else {
      isBinary=true;
      post=new PostMethod(url);
      httpMethod=eem=post;
    }
    // content type
    if(StringUtil.isEmpty(http.charset))http.charset=http.pageContext.getConfig().getWebCharset();
   
 
    boolean hasForm=false;
    boolean hasBody=false;
    boolean hasContentType=false;
  // Set http params
    ArrayList<NameValuePair> listQS=new ArrayList<NameValuePair>();
    ArrayList<Part> parts=new ArrayList<Part>();
    int len=http.params.size();
    StringBuilder acceptEncoding=new StringBuilder();
    for(int i=0;i<len;i++) {
      HttpParamBean param=http.params.get(i);
      String type=param.getType();
    // URL
      if(type.equals("url")) {
        listQS.add(new NameValuePair(translateEncoding(param.getName(), http.charset),translateEncoding(param.getValueAsString(), http.charset)));
      }
    // Form
      else if(type.equals("formfield") || type.equals("form")) {
        hasForm=true;
        if(http.method==METHOD_GET) throw new ApplicationException("httpparam type formfield can't only be used, when method of the tag http equal post");
        if(post!=null){
          if(doMultiPart){
            parts.add(new RailoStringPart(param.getName(),param.getValueAsString(),_charset));
          }
          else post.addParameter(new NameValuePair(param.getName(),param.getValueAsString()));
        }
        //else if(multi!=null)multi.addParameter(param.getName(),param.getValueAsString());
      }
    // CGI
      else if(type.equals("cgi")) {
        if(param.getEncoded())
            httpMethod.addRequestHeader(
                            translateEncoding(param.getName(),http.charset),
                            translateEncoding(param.getValueAsString(),http.charset));
                else
                    httpMethod.addRequestHeader(param.getName(),param.getValueAsString());
      }
        // Header
            else if(type.startsWith("head")) {
              if(param.getName().equalsIgnoreCase("content-type")) hasContentType=true;
             
              if(param.getName().equalsIgnoreCase("Accept-Encoding")) {
                acceptEncoding.append(headerValue(param.getValueAsString()));
                acceptEncoding.append(", ");
              }
              else httpMethod.addRequestHeader(param.getName(),headerValue(param.getValueAsString()));
            }
    // Cookie
      else if(type.equals("cookie")) {
        Cookie c=toCookie(_url.getHost(),param.getName(),param.getValueAsString(),_charset);
        c.setPath("/");
        client.getState().addCookie(c);
      }
    // File
      else if(type.equals("file")) {
        hasForm=true;
        if(http.method==METHOD_GET) throw new ApplicationException("httpparam type file can't only be used, when method of the tag http equal post");
        if(doMultiPart) {
          try {
            parts.add(new ResourcePart(param.getName(),new ResourcePartSource(param.getFile()),getContentType(param),_charset));
          }
          catch (FileNotFoundException e) {
            throw new ApplicationException("can't upload file, path is invalid",e.getMessage());
          }
        }
      }
    // XML
      else if(type.equals("xml")) {
        hasBody=true;
        hasContentType=true;
        httpMethod.addRequestHeader("Content-type", "text/xml; charset="+http.charset);
          //post.setRequestBody(new NameValuePair [] {new NameValuePair(translateEncoding(param.getName(), charset),translateEncoding(param.getValue(), charset))});
        if(eem==null)throw new ApplicationException("type xml is only supported for type post and put");
          eem.setRequestBody(param.getValueAsString());
      }
    // Body
      else if(type.equals("body")) {
        hasBody=true;
        if(eem==null)throw new ApplicationException("type body is only supported for type post and put");
          Object value = param.getValue();
         
          if(value instanceof InputStream) {
          eem.setRequestEntity(new InputStreamRequestEntity((InputStream)value,"application/octet-stream"));
        }
        else if(Decision.isCastableToBinary(value,false)){
          eem.setRequestEntity(new ByteArrayRequestEntity(Caster.toBinary(value)));
        }
        else {
          eem.setRequestEntity(new StringRequestEntity(param.getValueAsString()));
        }
      }
            else {
                throw new ApplicationException("invalid type ["+type+"]");
            }
       
    }
   
    httpMethod.setRequestHeader("Accept-Encoding",acceptEncoding.append("gzip").toString());
   
   
   
    // multipart
    if(doMultiPart && eem!=null) {
      hasContentType=true;
      boolean doIt=true;
      if(!http.multiPart && parts.size()==1){
        Part part = parts.get(0);
        /* jira 1513
          if(part instanceof ResourcePart){
          ResourcePart rp = (ResourcePart) part;
          eem.setRequestEntity(new ResourceRequestEntity(rp.getResource(),rp.getContentType()));
          doIt=false;
        }
        else */
          if(part instanceof RailoStringPart){
          RailoStringPart sp = (RailoStringPart) part;
          try {
            eem.setRequestEntity(new StringRequestEntity(sp.getValue(),sp.getContentType(),sp.getCharSet()));
          } catch (IOException e) {
            throw Caster.toPageException(e);
          }
          doIt=false;
        }
      }
      if(doIt)
        eem.setRequestEntity(new MultipartRequestEntityFlex(parts.toArray(new Part[parts.size()]), eem.getParams(),http.multiPartType));
    }
   
   
   
    if(hasBody && hasForm)
View Full Code Here

    private HttpMethodBase createMethod(HttpClient client, Request request) throws IOException, FileNotFoundException {
        String methodName = request.getMethod();
        HttpMethodBase method = null;
        if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
            EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl()) : new PutMethod(request.getUrl());

            String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

            post.getParams().setContentCharset("ISO-8859-1");
            if (request.getByteData() != null) {
                post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData()));
                post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length));
            } else if (request.getStringData() != null) {
                post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset));
                post.setRequestHeader("Content-Length", String.valueOf(request.getStringData().getBytes(bodyCharset).length));
            } else if (request.getStreamData() != null) {
                InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData());
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));

            } else if (request.getParams() != null) {
                StringBuilder sb = new StringBuilder();
                for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
                    final String key = paramEntry.getKey();
                    for (final String value : paramEntry.getValue()) {
                        if (sb.length() > 0) {
                            sb.append("&");
                        }
                        UTF8UrlEncoder.appendEncoded(sb, key);
                        sb.append("=");
                        UTF8UrlEncoder.appendEncoded(sb, value);
                    }
                }

                post.setRequestHeader("Content-Length", String.valueOf(sb.length()));
                post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1"));

                if (!request.getHeaders().containsKey("Content-Type")) {
                    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                }
            } else if (request.getParts() != null) {
                MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(), post.getParams());
                post.setRequestEntity(mre);
                post.setRequestHeader("Content-Type", mre.getContentType());
                post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength()));
            } else if (request.getEntityWriter() != null) {
                post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(), computeAndSetContentLength(request, post)));
            } else if (request.getFile() != null) {
                File file = request.getFile();
                if (!file.isFile()) {
                    throw new IOException(String.format(Thread.currentThread()
                            + "File %s is not a file or doesn't exist", file.getAbsolutePath()));
                }
                post.setRequestHeader("Content-Length", String.valueOf(file.length()));

                FileInputStream fis = new FileInputStream(file);
                try {
                    InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                    post.setRequestEntity(r);
                    post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
                } finally {
                    fis.close();
                }
            } else if (request.getBodyGenerator() != null) {
                Body body = request.getBodyGenerator().createBody();
                try {
                    int length = (int) body.getContentLength();
                    if (length < 0) {
                        length = (int) request.getContentLength();
                    }

                    // TODO: This is suboptimal
                    if (length >= 0) {
                        post.setRequestHeader("Content-Length", String.valueOf(length));

                        // This is totally sub optimal
                        byte[] bytes = new byte[length];
                        ByteBuffer buffer = ByteBuffer.wrap(bytes);
                        for (; ;) {
                            buffer.clear();
                            if (body.read(buffer) < 0) {
                                break;
                            }
                        }
                        post.setRequestEntity(new ByteArrayRequestEntity(bytes));
                    }
                } finally {
                    try {
                        body.close();
                    } catch (IOException e) {
                        logger.warn("Failed to close request body: {}", e.getMessage(), e);
                    }
                }
            }

            if (request.getHeaders().getFirstValue("Expect") != null
                    && request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) {
                post.setUseExpectHeader(true);
            }
            method = post;
        } else if (methodName.equalsIgnoreCase("DELETE")) {
            method = new DeleteMethod(request.getUrl());
        } else if (methodName.equalsIgnoreCase("HEAD")) {
View Full Code Here

            } else if (method.equals(HTTPConstants.TRACE)){
                httpMethod = new TraceMethod(urlStr);
            } else if (method.equals(HTTPConstants.OPTIONS)){
                httpMethod = new OptionsMethod(urlStr);
            } else if (method.equals(HTTPConstants.DELETE)){
                httpMethod = new EntityEnclosingMethod(urlStr) {
                    @Override
                    public String getName() { // HC3.1 does not have the method
                        return HTTPConstants.DELETE;
                    }
                };
            } else if (method.equals(HTTPConstants.GET)){
                httpMethod = new GetMethod(urlStr);
            } else if (method.equals(HTTPConstants.PATCH)){
                httpMethod = new EntityEnclosingMethod(urlStr) {
                    @Override
                    public String getName() { // HC3.1 does not have the method
                        return HTTPConstants.PATCH;
                    }
                };
View Full Code Here

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

        Header[] headers = conn.getHeaders();
        for (int i=0; i<headers.length; i++) {
            method.addRequestHeader(headers[i]);
        }
        if (method instanceof EntityEnclosingMethod) {
            EntityEnclosingMethod emethod = (EntityEnclosingMethod) method;
            emethod.setRequestBody(conn.getInputStream());
        }
        client.executeMethod(method);

       
        Header[] rheaders = method.getResponseHeaders();
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

        return mesResponse;
    }
   
    protected static HttpResponse post(String url, String user, String password, String body) throws IOException {
        HttpClient httpClient = new HttpClient();
        EntityEnclosingMethod method = new PostMethod(url);
        addAuthHeader(method, user, password);
       
        method.setRequestBody(body);
       
        String contentType = "application/xml; charset=utf-8";
        method.setRequestHeader("Content-type", contentType);
       
        int status = httpClient.executeMethod(method);
        InputStream responseBody = method.getResponseBodyAsStream();
       
        HttpResponse res = new HttpResponse(status, responseBody);
        return res;
    }
View Full Code Here

        return res;
    }
   
    protected static HttpResponse put(String url, String user, String password, String body) throws IOException {
        HttpClient httpClient = new HttpClient();
        EntityEnclosingMethod method = new PutMethod(url);
        addAuthHeader(method, user, password);
       
        method.setRequestBody(body);
       
        String contentType = "application/xml; charset=utf-8";
        method.setRequestHeader("Content-type", contentType);
       
        int status = httpClient.executeMethod(method);
        InputStream responseBody = method.getResponseBodyAsStream();
       
        HttpResponse res = new HttpResponse(status, responseBody);
        return res;
    }
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.