org.apache.commons.httpclient.methods.InputStreamRequestEntity Java Examples

The following examples show how to use org.apache.commons.httpclient.methods.InputStreamRequestEntity. 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: 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 #2
Source File: RemoteConnectorRequestImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void setRequestBody(InputStream body)
{
    requestBody = new InputStreamRequestEntity(body);
}
 
Example #3
Source File: HttpClientUtil.java    From AndroidRobot with Apache License 2.0 4 votes vote down vote up
/**
 * @param url
 * @param queryString 类似a=b&c=d 形式的参数
 * 
 * @param obj   发送到服务器的对象。
 *     
 * @return 服务器返回到客户端的对象。
 * @throws IOException
 */
public static String httpObjRequest(String url, Object obj, String queryString ) throws IOException
{
	String response = null;
	HttpClient client = new HttpClient();
    
    PostMethod post = new PostMethod(url);
    
    post.setQueryString(queryString);

    post.setRequestHeader("Content-Type", "application/octet-stream");

    java.io.ByteArrayOutputStream bOut = new java.io.ByteArrayOutputStream(1024);
    java.io.ByteArrayInputStream bInput = null;
    java.io.ObjectOutputStream out = null;
    
    try
    {
        out = new java.io.ObjectOutputStream(bOut);

        out.writeObject(obj);

        out.flush();
        out.close();

        out = null;

        bInput = new java.io.ByteArrayInputStream(bOut.toByteArray());

        RequestEntity re = new InputStreamRequestEntity(bInput);
        post.setRequestEntity(re);

        client.executeMethod(post);
        response = post.getResponseBodyAsString();
        System.out.println("URI:" + post.getURI());
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {
        if (out != null)
        {
            out.close();
            out = null;

        }

        if (bInput != null)
        {
            bInput.close();
            bInput = null;

        }
        //释放连接
        post.releaseConnection();
    }

    return response;

}
 
Example #4
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 #5
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;
}