Example usage for org.apache.commons.httpclient.methods RequestEntity getContentType

List of usage examples for org.apache.commons.httpclient.methods RequestEntity getContentType

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods RequestEntity getContentType.

Prototype

public abstract String getContentType();

Source Link

Usage

From source file:com.navercorp.pinpoint.plugin.httpclient3.HttpClient3EntityExtractor.java

@Override
public String getEntity(HttpMethod httpMethod) {
    if (httpMethod instanceof EntityEnclosingMethod) {
        final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;
        final RequestEntity entity = entityEnclosingMethod.getRequestEntity();
        if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
            try {
                String entityValue;
                String charSet = entityEnclosingMethod.getRequestCharSet();
                if (StringUtils.isEmpty(charSet)) {
                    charSet = HttpConstants.DEFAULT_CONTENT_CHARSET;
                }/*  w  ww .  jav a 2 s  .  co  m*/
                if (entity instanceof ByteArrayRequestEntity || entity instanceof StringRequestEntity) {
                    entityValue = entityUtilsToString(entity, charSet);
                } else {
                    entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")";
                }
                return entityValue;
            } catch (Exception e) {
                if (isDebug) {
                    logger.debug("Failed to get entity. httpMethod={}", httpMethod, e);
                }
            }
        }
    }
    return null;
}

From source file:com.dtolabs.client.utils.HttpClientChannel.java

/**
 * Perform the HTTP request.  Can only be performed once.
 *///from  w  w w.  j  a v  a 2s .  c  om
public void makeRequest() throws IOException, HttpClientException {
    if (requestMade) {
        return;
    }

    requestMade = true;
    RequestEntity reqEntity = null;
    NameValuePair[] postBody = null;
    if (isPostMethod()) {
        setMethodType("POST");
    }
    HttpMethod method = initMethod();
    if (isPostMethod()) {
        reqEntity = getRequestEntity((PostMethod) method);
        if (null != reqEntity) {
            logger.debug("preparing to post request entity data: " + reqEntity.getContentType());

            ((PostMethod) method).setRequestEntity(reqEntity);
        } else {
            logger.debug("preparing to post form data");
            postBody = getRequestBody((PostMethod) method);
            ((PostMethod) method).setRequestBody(postBody);
        }
    }
    logger.debug("calling preMakeRequest");
    if (!preMakeRequest(method)) {
        return;
    }
    logger.debug("calling doAuthentication...");
    if (!doAuthentication(method)) {
        return;
    }
    int bytesread = 0;
    try {
        if (!isPostMethod()) {
            method.setFollowRedirects(true);
        }
        logger.debug("make request...");
        resultCode = httpc.executeMethod(method);
        reasonCode = method.getStatusText();
        if (isPostMethod()) {
            //check redirect after post
            method = checkFollowRedirect(method, resultCode);
        }
        logger.debug("check needs reauth...");

        if (needsReAuthentication(resultCode, method)) {
            logger.debug("re-authentication needed, performing...");
            method.releaseConnection();
            method.abort();
            //need to re-authenticate.
            method = initMethod();
            if (isPostMethod() && null != reqEntity) {
                ((PostMethod) method).setRequestEntity(reqEntity);
            } else if (isPostMethod() && null != postBody) {
                ((PostMethod) method).setRequestBody(postBody);
            }
            if (!doAuthentication(method)) {
                //user login failed
                return;
            }
            //user login has succeeded
            logger.debug("remaking original request...");
            resultCode = httpc.executeMethod(method);
            reasonCode = method.getStatusText();
            if (needsReAuthentication(resultCode, method)) {
                //user request was unauthorized
                throw new HttpClientException("Unauthorized Action: "
                        + (null != method.getResponseHeader(Constants.X_RUNDECK_ACTION_UNAUTHORIZED_HEADER)
                                ? method.getResponseHeader(Constants.X_RUNDECK_ACTION_UNAUTHORIZED_HEADER)
                                        .getValue()
                                : reasonCode));
            }
        }

        logger.debug("finish...");
        if (null != method.getResponseHeader("Content-Type")) {
            resultType = method.getResponseHeader("Content-Type").getValue();
        }
        String type = resultType;
        if (type != null && type.indexOf(";") > 0) {
            type = type.substring(0, type.indexOf(";")).trim();
        }
        if (null == expectedContentType || expectedContentType.equals(type)) {
            if (null != destinationStream && resultCode >= 200 && resultCode < 300) {
                //read the input stream and write it to the destination
                contentLengthRetrieved = Streams.copyStreamCount(method.getResponseBodyAsStream(),
                        destinationStream);
            } else {
                final ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(1024 * 50);
                Streams.copyStream(method.getResponseBodyAsStream(), outputBytes);
                resultStream = new ByteArrayInputStream(outputBytes.toByteArray());
            }
        }
        reqMadeMethod = method;
    } catch (HttpException e) {
        logger.error("HTTP error: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }

    logger.debug("Response received");
    postMakeRequest();
}

From source file:com.navercorp.pinpoint.plugin.httpclient3.HttpClient3RequestTrace.java

@Override
public String getEntityValue() {
    if (httpMethod instanceof EntityEnclosingMethod) {
        final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;
        final RequestEntity entity = entityEnclosingMethod.getRequestEntity();
        if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
            try {
                String entityValue;
                String charSet = entityEnclosingMethod.getRequestCharSet();
                if (StringUtils.isEmpty(charSet)) {
                    charSet = HttpConstants.DEFAULT_CONTENT_CHARSET;
                }/*from   w  w  w.  j  a  va 2s.c o  m*/
                if (entity instanceof ByteArrayRequestEntity || entity instanceof StringRequestEntity) {
                    entityValue = entityUtilsToString(entity, charSet);
                } else {
                    entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")";
                }
                return entityValue;
            } catch (Exception e) {
                if (isDebug) {
                    logger.debug("Failed to get entity. httpMethod={}", this.httpMethod, e);
                }
            }
        }
    }
    return null;
}

From source file:com.esri.gpt.framework.http.HttpClientRequest.java

/**
 * Create the HTTP method.//from   w ww  .  j  a  v a 2s .  c  o  m
 * <br/>A GetMethod will be created if the RequestEntity associated with
 * the ContentProvider is null. Otherwise, a PostMethod will be created.
 * @return the HTTP method
 */
private HttpMethodBase createMethod() throws IOException {
    HttpMethodBase method = null;
    MethodName name = this.getMethodName();

    // make the method
    if (name == null) {
        if (this.getContentProvider() == null) {
            this.setMethodName(MethodName.GET);
            method = new GetMethod(this.getUrl());
        } else {
            this.setMethodName(MethodName.POST);
            method = new PostMethod(this.getUrl());
        }
    } else if (name.equals(MethodName.DELETE)) {
        method = new DeleteMethod(this.getUrl());
    } else if (name.equals(MethodName.GET)) {
        method = new GetMethod(this.getUrl());
    } else if (name.equals(MethodName.POST)) {
        method = new PostMethod(this.getUrl());
    } else if (name.equals(MethodName.PUT)) {
        method = new PutMethod(this.getUrl());
    }

    // write the request body if necessary
    if (this.getContentProvider() != null) {
        if (method instanceof EntityEnclosingMethod) {
            EntityEnclosingMethod eMethod = (EntityEnclosingMethod) method;
            RequestEntity eAdapter = getContentProvider() instanceof MultiPartContentProvider
                    ? new MultiPartProviderAdapter(this, eMethod,
                            (MultiPartContentProvider) getContentProvider())
                    : new ApacheEntityAdapter(this, this.getContentProvider());
            eMethod.setRequestEntity(eAdapter);
            if (eAdapter.getContentType() != null) {
                eMethod.setRequestHeader("Content-type", eAdapter.getContentType());
            }
        } else {
            // TODO: possibly will need an exception here in the future
        }
    }

    // set headers, add the retry method
    for (Map.Entry<String, String> hdr : this.requestHeaders.entrySet()) {
        method.addRequestHeader(hdr.getKey(), hdr.getValue());
    }

    // declare possible gzip handling
    method.setRequestHeader("Accept-Encoding", "gzip");

    this.addRetryHandler(method);
    return method;
}

From source file:com.baidu.oped.apm.profiler.modifier.connector.httpclient3.interceptor.ExecuteInterceptor.java

private void recordEntity(HttpMethod httpMethod, Trace trace) {
    if (httpMethod instanceof EntityEnclosingMethod) {
        final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;
        final RequestEntity entity = entityEnclosingMethod.getRequestEntity();

        if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
            if (entitySampler.isSampling()) {
                try {
                    String entityValue;
                    String charSet = entityEnclosingMethod.getRequestCharSet();

                    if (charSet == null || charSet.isEmpty()) {
                        charSet = HttpConstants.DEFAULT_CONTENT_CHARSET;
                    }//from   w w  w  .  ja v a 2 s.  c o m
                    if (entity instanceof ByteArrayRequestEntity) {
                        entityValue = readByteArray((ByteArrayRequestEntity) entity, charSet);
                    } else if (entity instanceof StringRequestEntity) {
                        entityValue = readString((StringRequestEntity) entity);
                    } else {
                        entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")";
                    }

                    trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, entityValue);
                } catch (Exception e) {
                    logger.debug("HttpEntityEnclosingRequest entity record fail. Caused:{}", e.getMessage(), e);
                }
            }
        }
    }

}

From source file:org.apache.camel.component.http.HttpProducer.java

/**
 * Creates the HttpMethod to use to call the remote server, either its GET or POST.
 *
 * @param exchange the exchange// w w w . j a  v  a 2 s  . co  m
 * @return the created method as either GET or POST
 * @throws CamelExchangeException is thrown if error creating RequestEntity
 */
@SuppressWarnings("deprecation")
protected HttpMethod createMethod(Exchange exchange) throws Exception {
    // creating the url to use takes 2-steps
    String url = HttpHelper.createURL(exchange, getEndpoint());
    URI uri = HttpHelper.createURI(exchange, url, getEndpoint());
    // get the url and query string from the uri
    url = uri.toASCIIString();
    String queryString = uri.getRawQuery();

    // execute any custom url rewrite
    String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this);
    if (rewriteUrl != null) {
        // update url and query string from the rewritten url
        url = rewriteUrl;
        uri = new URI(url);
        // use raw query to have uri decimal encoded which http client requires
        queryString = uri.getRawQuery();
    }

    // remove query string as http client does not accept that
    if (url.indexOf('?') != -1) {
        url = url.substring(0, url.indexOf('?'));
    }

    // create http holder objects for the request
    RequestEntity requestEntity = createRequestEntity(exchange);
    HttpMethods methodToUse = HttpHelper.createMethod(exchange, getEndpoint(), requestEntity != null);
    HttpMethod method = methodToUse.createMethod(url);
    if (queryString != null) {
        // need to encode query string
        queryString = UnsafeUriCharactersEncoder.encode(queryString);
        method.setQueryString(queryString);
    }

    LOG.trace("Using URL: {} with method: {}", url, method);

    if (methodToUse.isEntityEnclosing()) {
        ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
        if (requestEntity != null && requestEntity.getContentType() == null) {
            LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange);
        }
    }

    // there must be a host on the method
    if (method.getHostConfiguration().getHost() == null) {
        throw new IllegalArgumentException("Invalid uri: " + url
                + ". If you are forwarding/bridging http endpoints, then enable the bridgeEndpoint option on the endpoint: "
                + getEndpoint());
    }

    return method;
}

From source file:org.apache.servicemix.http.processors.ProviderProcessor.java

public void process(MessageExchange exchange) throws Exception {
    if (exchange.getStatus() == ExchangeStatus.DONE || exchange.getStatus() == ExchangeStatus.ERROR) {
        PostMethod method = methods.remove(exchange.getExchangeId());
        if (method != null) {
            method.releaseConnection();//  w w  w  .  ja  va  2 s .c  om
        }
        return;
    }
    boolean txSync = exchange.isTransacted()
            && Boolean.TRUE.equals(exchange.getProperty(JbiConstants.SEND_SYNC));
    txSync |= endpoint.isSynchronous();
    NormalizedMessage nm = exchange.getMessage("in");
    if (nm == null) {
        throw new IllegalStateException("Exchange has no input message");
    }

    String locationURI = endpoint.getLocationURI();

    // Incorporated because of JIRA SM-695
    Object newDestinationURI = nm.getProperty(JbiConstants.HTTP_DESTINATION_URI);
    if (newDestinationURI != null) {
        locationURI = (String) newDestinationURI;
        log.debug("Location URI overridden: " + locationURI);
    }

    PostMethod method = new PostMethod(getRelUri(locationURI));
    SoapMessage soapMessage = new SoapMessage();
    soapHelper.getJBIMarshaler().fromNMS(soapMessage, nm);
    Context context = soapHelper.createContext(soapMessage);
    soapHelper.onSend(context);
    SoapWriter writer = soapHelper.getSoapMarshaler().createWriter(soapMessage);
    copyHeaderInformation(nm, method);
    RequestEntity entity = writeMessage(writer);
    // remove content-type header that may have been part of the in message
    if (!endpoint.isWantContentTypeHeaderFromExchangeIntoHttpRequest()) {
        method.removeRequestHeader(HEADER_CONTENT_TYPE);
        method.addRequestHeader(HEADER_CONTENT_TYPE, entity.getContentType());
    }
    if (entity.getContentLength() < 0) {
        method.removeRequestHeader(HEADER_CONTENT_LENGTH);
    } else {
        method.setRequestHeader(HEADER_CONTENT_LENGTH, Long.toString(entity.getContentLength()));
    }
    if (endpoint.isSoap() && method.getRequestHeader(HEADER_SOAP_ACTION) == null) {
        if (endpoint.getSoapAction() != null) {
            method.setRequestHeader(HEADER_SOAP_ACTION, endpoint.getSoapAction());
        } else {
            //                method.setRequestHeader(HEADER_SOAP_ACTION, "\"\"");
        }
    }
    method.setRequestHeader(HEADER_X_CORRELATION_ID,
            (String) exchange.getProperty(JbiConstants.CORRELATION_ID));
    String smxInstanceName = System.getProperty(SMX_INSTANCE_NAME_PROPERTY);
    if (smxInstanceName != null) {
        method.setRequestHeader(HEADER_X_POWERED_BY, smxInstanceName);
    } else {
        log.warn(SMX_INSTANCE_NAME_PROPERTY + " property was not set in servicemix.xml file");
    }

    method.setRequestEntity(entity);
    boolean close = true;
    try {
        // Set the retry handler
        int retries = getConfiguration().isStreamingEnabled() ? 0 : getConfiguration().getRetryCount();
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(retries, true));
        // Set authentication
        if (endpoint.getBasicAuthentication() != null) {
            endpoint.getBasicAuthentication().applyCredentials(getClient(), exchange, nm);
        }
        // Execute the HTTP method
        //method.getParams().setLongParameter(HttpConnectionParams.CONNECTION_TIMEOUT, getClient().getParams().getSoTimeout());

        int response = -1;
        try {
            response = getClient().executeMethod(getHostConfiguration(locationURI, exchange, nm), method);
        } catch (Exception ex) {
            try {
                if (listener != null) {
                    if (ex instanceof SocketException) {
                        log.error("Connection to address: " + locationURI + " was refused");
                        listener.onConnectionRefused(locationURI);
                    } else if (ex instanceof SocketTimeoutException) {
                        log.error("Connection to address: " + locationURI + " timed out");
                        listener.onTimeout(locationURI);
                    }
                }
            } catch (Exception ex2) {
                log.warn("Error in HttpConnectionListener: " + ex2.getMessage());
            } finally {
                throw ex;
            }
        }
        try {
            if (listener != null) {
                listener.onPostExecuted(locationURI, response);
            }
        } catch (Exception ex) {
            log.warn("Error in HttpConnectionListener: " + ex.getMessage());
        }
        if (response != HttpStatus.SC_OK && response != HttpStatus.SC_ACCEPTED) {
            if (!(exchange instanceof InOnly)) {
                SoapReader reader = soapHelper.getSoapMarshaler().createReader();
                Header contentType = method.getResponseHeader(HEADER_CONTENT_TYPE);
                String content = convertResponseBodyToString(method);
                logInOut(locationURI, response, method, soapMessage, content);
                soapMessage = reader.read(new ByteArrayInputStream(content.getBytes()),
                        contentType != null ? contentType.getValue() : null);
                context.setFaultMessage(soapMessage);
                soapHelper.onAnswer(context);
                Fault fault = exchange.createFault();
                fault.setProperty(JbiConstants.PROTOCOL_HEADERS, getHeaders(method));
                soapHelper.getJBIMarshaler().toNMS(fault, soapMessage);
                exchange.setFault(fault);
                if (txSync) {
                    channel.sendSync(exchange);
                } else {
                    methods.put(exchange.getExchangeId(), method);
                    channel.send(exchange);
                    close = false;
                }
                return;
            } else {
                String content = convertResponseBodyToString(method);
                // even if it is InOnly, some out could come to us
                logInOut(locationURI, response, method, soapMessage, content);
                throw new Exception("Invalid status response: " + response);
            }
        }
        if (exchange instanceof InOut) {
            close = processInOut(exchange, method, context, txSync, close);
        } else if (exchange instanceof InOptionalOut) {
            close = processInOptionalOut(method, exchange, context, txSync, close);
        } else {
            exchange.setStatus(ExchangeStatus.DONE);
            channel.send(exchange);
        }
    } finally {
        if (close) {
            method.releaseConnection();
        }
    }
}

From source file:org.pentaho.di.baserver.utils.web.HttpConnectionHelperTest.java

@Test
public void testGetHttpMethod() throws Exception {
    Map<String, String> queryParameters = new HashMap<String, String>();
    queryParameters.put("param1", "value1");
    queryParameters.put("param2", "value2");
    queryParameters.put("param3", "value3");
    String url = "http://localhost:8080/pentaho";

    HttpMethod method = httpConnectionHelperSpy.getHttpMethod(url, queryParameters, "GET");
    assertEquals(method.getClass(), GetMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    assertNotNull(method.getQueryString());

    method = httpConnectionHelperSpy.getHttpMethod(url, queryParameters, "PUT");
    assertEquals(method.getClass(), PutMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    RequestEntity requestEntity = ((PutMethod) method).getRequestEntity();
    assertNotNull(requestEntity);/*from ww w  . j av  a  2 s.c  o  m*/
    assertEquals(requestEntity.getContentType(), "application/x-www-form-urlencoded; charset=UTF-8");
    assertNull(method.getQueryString());
    assertEquals(requestEntity.getClass(), StringRequestEntity.class);
    assertNotNull(((StringRequestEntity) requestEntity).getContent());

    method = httpConnectionHelperSpy.getHttpMethod(url, queryParameters, "POST");
    assertEquals(method.getClass(), PostMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    requestEntity = ((PostMethod) method).getRequestEntity();
    assertNotNull(requestEntity);
    assertEquals(requestEntity.getContentType(), "application/x-www-form-urlencoded; charset=UTF-8");
    assertNull(method.getQueryString());
    assertEquals(requestEntity.getClass(), StringRequestEntity.class);
    assertNotNull(((StringRequestEntity) requestEntity).getContent());

    // POST without parameters
    method = httpConnectionHelperSpy.getHttpMethod(url, null, "POST");
    assertEquals(method.getClass(), PostMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    requestEntity = ((PostMethod) method).getRequestEntity();
    assertNotNull(requestEntity);
    assertEquals(requestEntity.getContentType(), "application/x-www-form-urlencoded; charset=UTF-8");
    assertNull(method.getQueryString());
    assertEquals(requestEntity.getClass(), StringRequestEntity.class);
    assertNotNull(((StringRequestEntity) requestEntity).getContent());

    method = httpConnectionHelperSpy.getHttpMethod(url, queryParameters, "DELETE");
    assertEquals(method.getClass(), DeleteMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    assertNotNull(method.getQueryString());

    method = httpConnectionHelperSpy.getHttpMethod(url, queryParameters, "HEAD");
    assertEquals(method.getClass(), HeadMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    assertNotNull(method.getQueryString());

    method = httpConnectionHelperSpy.getHttpMethod(url, queryParameters, "OPTIONS");
    assertEquals(method.getClass(), OptionsMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    assertNotNull(method.getQueryString());
}