Java Code Examples for org.apache.commons.httpclient.methods.EntityEnclosingMethod#setRequestEntity()

The following examples show how to use org.apache.commons.httpclient.methods.EntityEnclosingMethod#setRequestEntity() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void sendRequest() throws IOException {
  synchronized(lock) {
    if (out != null) {
      if (!(resCache instanceof EntityEnclosingMethod)) {
        System.err.println("Warning: data written to request's body, "
                           +"but not supported");
      } else {
        EntityEnclosingMethod m = (EntityEnclosingMethod) resCache;
        m.setRequestEntity(new ByteArrayRequestEntity(out.getBytes()));
      }
    }

    client.executeMethod(resCache);
    requestSent = true;
  }
}
 
Example 2
Source File: HttpUtilities.java    From odo with Apache License 2.0 6 votes vote down vote up
/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data
 * as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a
 * multipart POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains the multipart
 * POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 */
@SuppressWarnings("unchecked")
public static void handleMultipartPost(
    EntityEnclosingMethod postMethodProxyRequest,
    HttpServletRequest httpServletRequest,
    DiskFileItemFactory diskFileItemFactory)
    throws ServletException {
    // TODO: this function doesn't set any history data
    try {
        // just pass back the binary data
        InputStreamRequestEntity ire = new InputStreamRequestEntity(httpServletRequest.getInputStream());
        postMethodProxyRequest.setRequestEntity(ire);
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, httpServletRequest.getHeader(STRING_CONTENT_TYPE_HEADER_NAME));
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
 
Example 3
Source File: AuthenticatedHttp.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Adds the JSON as request-body the the method and sets the correct
 * content-type.
 * @param method EntityEnclosingMethod
 * @param object JSONObject
 */
private void populateRequestBody(EntityEnclosingMethod method, JSONObject object)
{
    try
    {
        method.setRequestEntity(new StringRequestEntity(object.toJSONString(), MIME_TYPE_JSON, "UTF-8"));
    }
    catch (UnsupportedEncodingException error)
    {
        // This will never happen!
        throw new RuntimeException("All hell broke loose, a JVM that doesn't have UTF-8 encoding...");
    }
}
 
Example 4
Source File: CloudMetadataScanner.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private static HttpMethod createRequestMethod(
        HttpRequestHeader header, HttpBody body, HttpMethodParams params) throws URIException {
    HttpMethod httpMethod = new ZapGetMethod();
    httpMethod.setURI(header.getURI());
    httpMethod.setParams(params);
    params.setVersion(HttpVersion.HTTP_1_1);

    String msg = header.getHeadersAsString();

    String[] split = Pattern.compile("\\r\\n", Pattern.MULTILINE).split(msg);
    String token = null;
    String name = null;
    String value = null;

    int pos = 0;
    for (int i = 0; i < split.length; i++) {
        token = split[i];
        if (token.equals("")) {
            continue;
        }

        if ((pos = token.indexOf(":")) < 0) {
            return null;
        }
        name = token.substring(0, pos).trim();
        value = token.substring(pos + 1).trim();
        httpMethod.addRequestHeader(name, value);
    }
    if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) {
        EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod;
        post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
    }
    httpMethod.setFollowRedirects(false);
    return httpMethod;
}
 
Example 5
Source File: ClientEntry.java    From rome with Apache License 2.0 5 votes vote down vote up
/**
 * Update entry by posting new representation of entry to server. Note that you should not
 * attempt to update entries that you get from iterating over a collection they may be "partial"
 * entries. If you want to update an entry, you must get it via one of the
 * <code>getEntry()</code> methods in {@link com.rometools.rome.propono.atom.common.Collection}
 * or {@link com.rometools.rome.propono.atom.common.AtomService}.
 *
 * @throws ProponoException If entry is a "partial" entry.
 */
public void update() throws ProponoException {
    if (partial) {
        throw new ProponoException("ERROR: attempt to update partial entry");
    }
    final EntityEnclosingMethod method = new PutMethod(getEditURI());
    addAuthentication(method);
    final StringWriter sw = new StringWriter();
    final int code = -1;
    try {
        Atom10Generator.serializeEntry(this, sw);
        method.setRequestEntity(new StringRequestEntity(sw.toString(), null, null));
        method.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8");
        getHttpClient().executeMethod(method);
        final InputStream is = method.getResponseBodyAsStream();
        if (method.getStatusCode() != 200 && method.getStatusCode() != 201) {
            throw new ProponoException("ERROR HTTP status=" + method.getStatusCode() + " : " + Utilities.streamToString(is));
        }

    } catch (final Exception e) {
        final String msg = "ERROR: updating entry, HTTP code: " + code;
        LOG.debug(msg, e);
        throw new ProponoException(msg, e);
    } finally {
        method.releaseConnection();
    }
}
 
Example 6
Source File: ClientEntry.java    From rome with Apache License 2.0 5 votes vote down vote up
void addToCollection(final ClientCollection col) throws ProponoException {
    setCollection(col);
    final EntityEnclosingMethod method = new PostMethod(getCollection().getHrefResolved());
    addAuthentication(method);
    final StringWriter sw = new StringWriter();
    int code = -1;
    try {
        Atom10Generator.serializeEntry(this, sw);
        method.setRequestEntity(new StringRequestEntity(sw.toString(), null, null));
        method.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8");
        getHttpClient().executeMethod(method);
        final InputStream is = method.getResponseBodyAsStream();
        code = method.getStatusCode();
        if (code != 200 && code != 201) {
            throw new ProponoException("ERROR HTTP status=" + code + " : " + Utilities.streamToString(is));
        }
        final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(is), getCollection().getHrefResolved(), Locale.US);
        BeanUtils.copyProperties(this, romeEntry);

    } catch (final Exception e) {
        final String msg = "ERROR: saving entry, HTTP code: " + code;
        LOG.debug(msg, e);
        throw new ProponoException(msg, e);
    } finally {
        method.releaseConnection();
    }
    final Header locationHeader = method.getResponseHeader("Location");
    if (locationHeader == null) {
        LOG.warn("WARNING added entry, but no location header returned");
    } else if (getEditURI() == null) {
        final List<Link> links = getOtherLinks();
        final Link link = new Link();
        link.setHref(locationHeader.getValue());
        link.setRel("edit");
        links.add(link);
        setOtherLinks(links);
    }
}
 
Example 7
Source File: HttpMethodCloner.java    From http4e with Apache License 2.0 4 votes vote down vote up
private static void copyEntityEnclosingMethod(
 EntityEnclosingMethod m, EntityEnclosingMethod copy )
   throws java.io.IOException
{
    copy.setRequestEntity(m.getRequestEntity());
}
 
Example 8
Source File: ClientMediaEntry.java    From rome with Apache License 2.0 4 votes vote down vote up
/** Package access, to be called by DefaultClientCollection */
@Override
void addToCollection(final ClientCollection col) throws ProponoException {
    setCollection(col);
    final EntityEnclosingMethod method = new PostMethod(col.getHrefResolved());
    getCollection().addAuthentication(method);
    try {
        final Content c = getContents().get(0);
        if (inputStream != null) {
            method.setRequestEntity(new InputStreamRequestEntity(inputStream));
        } else {
            method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(getBytes())));
        }
        method.setRequestHeader("Content-type", c.getType());
        method.setRequestHeader("Title", getTitle());
        method.setRequestHeader("Slug", getSlug());
        getCollection().getHttpClient().executeMethod(method);
        if (inputStream != null) {
            inputStream.close();
        }
        final InputStream is = method.getResponseBodyAsStream();
        if (method.getStatusCode() == 200 || method.getStatusCode() == 201) {
            final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(is), col.getHrefResolved(), Locale.US);
            BeanUtils.copyProperties(this, romeEntry);

        } else {
            throw new ProponoException("ERROR HTTP status-code=" + method.getStatusCode() + " status-line: " + method.getStatusLine());
        }
    } catch (final IOException ie) {
        throw new ProponoException("ERROR: saving media entry", ie);
    } catch (final JDOMException je) {
        throw new ProponoException("ERROR: saving media entry", je);
    } catch (final FeedException fe) {
        throw new ProponoException("ERROR: saving media entry", fe);
    } catch (final IllegalAccessException ae) {
        throw new ProponoException("ERROR: saving media entry", ae);
    } catch (final InvocationTargetException te) {
        throw new ProponoException("ERROR: saving media entry", te);
    }
    final Header locationHeader = method.getResponseHeader("Location");
    if (locationHeader == null) {
        LOG.warn("WARNING added entry, but no location header returned");
    } else if (getEditURI() == null) {
        final List<Link> links = getOtherLinks();
        final Link link = new Link();
        link.setHref(locationHeader.getValue());
        link.setRel("edit");
        links.add(link);
        setOtherLinks(links);
    }
}
 
Example 9
Source File: HttpUtil.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>
 *
 * @param httpMethod the HTTP method to use
 * @param url the url to execute (in milliseconds)
 * @param httpHeaders optional HTTP headers which has to be set on request
 * @param content the content to be send to the given <code>url</code> or
 *            <code>null</code> if no content should be send.
 * @param contentType the content type of the given <code>content</code>
 * @param timeout the socket timeout to wait for data
 * @param proxyHost the hostname of the proxy
 * @param proxyPort the port of the proxy
 * @param proxyUser the username to authenticate with the proxy
 * @param proxyPassword the password to authenticate with the proxy
 * @param nonProxyHosts the hosts that won't be routed through the proxy
 * @return the response body or <code>NULL</code> when the request went wrong
 */
public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser,
        String proxyPassword, String nonProxyHosts) {

    HttpClient client = new HttpClient();

    // only configure a proxy if a host is provided
    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (StringUtils.isNotBlank(proxyUser)) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
    }

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    if (httpHeaders != null) {
        for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
            method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
        }
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && content != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    Credentials credentials = extractCredentials(url);
    if (credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.debug("About to execute '{}'", method.getURI());
        } catch (URIException e) {
            logger.debug("{}", e.getMessage());
        }
    }

    try {

        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.debug("Method failed: {}", method.getStatusLine());
        }

        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug("{}", responseBody);
        }

        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }

    return null;
}