Package org.apache.commons.httpclient

Examples of org.apache.commons.httpclient.HttpMethod


            // fallback to POST if data, otherwise GET
            methodToUse = requestEntity != null ? HttpMethods.POST : HttpMethods.GET;
        }

        String uri = ((HttpEndpoint)getEndpoint()).getHttpUri().toString();
        HttpMethod method = methodToUse.createMethod(uri);

        if (queryString != null) {
            method.setQueryString(queryString);
        }
        if (methodToUse.isEntityEnclosing()) {
            ((EntityEnclosingMethod)method).setRequestEntity(requestEntity);
        }
View Full Code Here


  }

  /** {@inheritDoc} */
  public HttpResponse fetch(HttpRequest request) {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod;
    String methodType = request.getMethod();
    String requestUri = request.getUri().toString();

    // Select a proxy based on the URI. May be Proxy.NO_PROXY
    Proxy proxy = ProxySelector.getDefault().select(request.getUri().toJavaUri()).get(0);

    if (proxy != Proxy.NO_PROXY) {
      InetSocketAddress address = (InetSocketAddress) proxy.address();
      httpClient.getHostConfiguration().setProxy(address.getHostName(), address.getPort());
    }

    if ("POST".equals(methodType) || "PUT".equals(methodType)) {
      EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType))
              ? new PostMethod(requestUri)
              : new PutMethod(requestUri);

      if (request.getPostBodyLength() > 0) {
        enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody()));
        enclosingMethod.setRequestHeader("Content-Length",
            String.valueOf(request.getPostBodyLength()));
      }
      httpMethod = enclosingMethod;
    } else if ("DELETE".equals(methodType)) {
      httpMethod = new DeleteMethod(requestUri);
    } else {
      httpMethod = new GetMethod(requestUri);
    }

    httpMethod.setFollowRedirects(false);
    httpMethod.getParams().setSoTimeout(connectionTimeoutMs);
    httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");

    for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
      httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
    }

    try {

      int statusCode = httpClient.executeMethod(httpMethod);

      // Handle redirects manually
      if (request.getFollowRedirects() &&
          ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) ||
          (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) ||
          (statusCode == HttpStatus.SC_SEE_OTHER) ||
          (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) {

        Header header = httpMethod.getResponseHeader("location");
        if (header != null) {
            String redirectUri = header.getValue();

            if ((redirectUri == null) || (redirectUri.equals(""))) {
                redirectUri = "/";
            }
            httpMethod.releaseConnection();
            httpMethod = new GetMethod(redirectUri);

            statusCode = httpClient.executeMethod(httpMethod);
        }
      }

      return makeResponse(httpMethod, statusCode);

    } catch (IOException e) {
      if (e instanceof java.net.SocketTimeoutException ||
          e instanceof java.net.SocketException) {
        return HttpResponse.timeout();
      }

      return HttpResponse.error();

    } finally {
      httpMethod.releaseConnection();
    }
  }
View Full Code Here

        final InputStream body = request.getBody();
        final boolean isDelete = DELETE.equalsIgnoreCase(method);
        final boolean isPost = POST.equalsIgnoreCase(method);
        final boolean isPut = PUT.equalsIgnoreCase(method);
        byte[] excerpt = null;
        HttpMethod httpMethod;
        if (isPost || isPut) {
            EntityEnclosingMethod entityEnclosingMethod =
                isPost ? new PostMethod(url) : new PutMethod(url);
            if (body != null) {
                ExcerptInputStream e = new ExcerptInputStream(body);
                String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH);
                entityEnclosingMethod.setRequestEntity((length == null)
                        ? new InputStreamRequestEntity(e)
                        : new InputStreamRequestEntity(e, Long.parseLong(length)));
                excerpt = e.getExcerpt();
            }
            httpMethod = entityEnclosingMethod;
        } else if (isDelete) {
            httpMethod = new DeleteMethod(url);
        } else {
            httpMethod = new GetMethod(url);
        }
        for (Map.Entry<String, Object> p : parameters.entrySet()) {
            String name = p.getKey();
            String value = p.getValue().toString();
            if (FOLLOW_REDIRECTS.equals(name)) {
                httpMethod.setFollowRedirects(Boolean.parseBoolean(value));
            } else if (READ_TIMEOUT.equals(name)) {
                httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value));
            }
        }
        for (Map.Entry<String, String> header : request.headers) {
            httpMethod.addRequestHeader(header.getKey(), header.getValue());
        }
        HttpClient client = clientPool.getHttpClient(new URL(httpMethod
                .getURI().toString()));
        client.executeMethod(httpMethod);
        return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset());
    }
View Full Code Here

* @author rdionne@google.com (Robert Dionne)
*/
public class GatewayMethodTest extends TestCase {

  public void testGetNameAndGetUri() throws Exception {
    HttpMethod method = new GatewayMethod("GET", "http://www.google.com/search");
    assertEquals("GET", method.getName());
    assertEquals("http://www.google.com/search", method.getURI().toString());
  }
View Full Code Here

   * Does a basic HTTP GET and returns Http Status code + response body
   * Will add the dummy user query string
   */
  private static MethodCallRetVal doHttpCall(String uri, HTTP_METHOD_TYPE type, Map<String, Object> data, NameValuePair[] params) throws IOException {
    HttpClient client = new HttpClient();
    HttpMethod method;
    switch (type) {
    case GET:
      method = new GetMethod(uri);
      break;
    case DELETE:
      method = new DeleteMethod(uri);
      break;
    case PUT:
      method = new PutMethod(uri);
      if(data == null) {
        break;
      }
      String msgBody = JsonBuilder.mapToJson(data);
      LOG.info("Msg Body: " + msgBody);
      StringRequestEntity sre = new StringRequestEntity(msgBody, "application/json", charSet);
      ((PutMethod)method).setRequestEntity(sre);
      break;
    default:
      throw new IllegalArgumentException("Unsupported method type: " + type);
    }
    if(params == null) {
      method.setQueryString(new NameValuePair[] {new NameValuePair("user.name", username)});
    }
    else {
      NameValuePair[] newParams = new NameValuePair[params.length + 1];
      System.arraycopy(params, 0, newParams, 1, params.length);
      newParams[0] = new NameValuePair("user.name", username);
      method.setQueryString(newParams);
    }
    String actualUri = "no URI";
    try {
      actualUri = method.getURI().toString();//should this be escaped string?
      LOG.debug(type + ": " + method.getURI().getEscapedURI());
      int httpStatus = client.executeMethod(method);
      LOG.debug("Http Status Code=" + httpStatus);
      String resp = method.getResponseBodyAsString();
      LOG.debug("response: " + resp);
      return new MethodCallRetVal(httpStatus, resp, actualUri, method.getName());
    }
    catch (IOException ex) {
      LOG.error("doHttpCall() failed", ex);
    }
    finally {
      method.releaseConnection();
    }
    return new MethodCallRetVal(-1, "Http " + type + " failed; see log file for details", actualUri, method.getName());
  }
View Full Code Here

        }
       
    }
   
    public void testPostBody() throws Exception {
        HttpMethod method = new GetMethod("http://localhost:9080/users/homer?" + QUERY_STRING);
        try {
            HttpClient client = new HttpClient();
            assertEquals(200, client.executeMethod(method));
        } finally {
            method.releaseConnection();
        }

    }
View Full Code Here

            }
        };
    }
   
    public void testCustomResponse() throws Exception {
        HttpMethod method = new PostMethod("http://localhost:9080/users/homer");
        try {
            HttpClient client = new HttpClient();
            assertEquals(417, client.executeMethod(method));
            assertTrue(method.getResponseHeader("Content-Type").getValue()
                    .startsWith("application/JSON"));
        } finally {
            method.releaseConnection();
        }

    }
View Full Code Here

        }
       
    }
   
    public void testPostBody() throws Exception {
        HttpMethod method = new PostMethod("http://localhost:9080/users/homer");
        try {
            RequestEntity requestEntity = new StringRequestEntity(MSG_BODY, null, null);
            ((EntityEnclosingMethod)method).setRequestEntity(requestEntity);
            HttpClient client = new HttpClient();
            assertEquals(200, client.executeMethod(method));
        } finally {
            method.releaseConnection();
        }

    }
View Full Code Here

        super(endpoint);
        httpClient = endpoint.createHttpClient();
    }

    public void process(Exchange exchange) throws Exception {
        HttpMethod method = createMethod(exchange);
        Message in = exchange.getIn();
        HeaderFilterStrategy strategy = ((HttpEndpoint)getEndpoint()).getHeaderFilterStrategy();

        // propagate headers as HTTP headers
        for (String headerName : in.getHeaders().keySet()) {
            String headerValue = in.getHeader(headerName, String.class);
            if (strategy != null && !strategy.applyFilterToCamelHeaders(headerName, headerValue)) {
                method.addRequestHeader(headerName, headerValue);
            }
        }

        // lets store the result in the output message.
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Executing http " + method.getName() + " method: " + method.getURI().toString());
            }
            int responseCode = executeMethod(method);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Http responseCode: " + responseCode);
            }

            if (responseCode >= 100 && responseCode < 300) {
                Message answer = exchange.getOut(true);

                answer.setHeaders(in.getHeaders());
                answer.setHeader(HTTP_RESPONSE_CODE, responseCode);
                answer.setBody(extractResponseBody(method));

                // propagate HTTP response headers
                Header[] headers = method.getResponseHeaders();
                for (Header header : headers) {
                    String name = header.getName();
                    String value = header.getValue();
                    if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value)) {
                        answer.setHeader(name, value);
                    }
                }
            } else {
                HttpOperationFailedException exception = null;
                Header[] headers = method.getResponseHeaders();
                InputStream is =  extractResponseBody(method);
                if (responseCode >= 300 && responseCode < 400) {
                    String redirectLocation;
                    Header locationHeader = method.getResponseHeader("location");
                    if (locationHeader != null) {
                        redirectLocation = locationHeader.getValue();
                        exception = new HttpOperationFailedException(responseCode, method.getStatusLine(), redirectLocation, headers, is);
                    } else {
                        // no redirect location
                        exception = new HttpOperationFailedException(responseCode, method.getStatusLine(), headers, is);
                    }
                } else {
                    // internal server error (error code 500)
                    exception = new HttpOperationFailedException(responseCode, method.getStatusLine(), headers, is);
                }

                if (exception != null) {                   
                    throw exception;
                }
            }

        } finally {
            method.releaseConnection();
        }
    }
View Full Code Here

        String uri = exchange.getIn().getHeader(HTTP_URI, String.class);
        if (uri == null) {
            uri = ((HttpEndpoint)getEndpoint()).getHttpUri().toString();
        }

        HttpMethod method = methodToUse.createMethod(uri);

        if (queryString != null) {
            method.setQueryString(queryString);
        }
        if (methodToUse.isEntityEnclosing()) {
            ((EntityEnclosingMethod)method).setRequestEntity(requestEntity);
        }
View Full Code Here

TOP

Related Classes of org.apache.commons.httpclient.HttpMethod

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.