Example usage for org.apache.http.entity InputStreamEntity InputStreamEntity

List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity

Introduction

In this page you can find the example usage for org.apache.http.entity InputStreamEntity InputStreamEntity.

Prototype

public InputStreamEntity(InputStream inputStream, ContentType contentType) 

Source Link

Usage

From source file:org.graphity.core.util.jena.HttpOp.java

/**
 * Executes a HTTP PUT operation/*from w ww  .j a va2 s. c  om*/
 * 
 * @param url
 *            URL
 * @param contentType
 *            Content Type for the PUT
 * @param input
 *            Input Stream to read PUT content from
 * @param length
 *            Amount of content to PUT
 * @param httpClient
 *            HTTP Client
 * @param httpContext
 *            HTTP Context
 * @param authenticator
 *            HTTP Authenticator
 */
public static void execHttpPut(String url, String contentType, InputStream input, long length,
        HttpClient httpClient, HttpContext httpContext, HttpAuthenticator authenticator) {
    InputStreamEntity e = new InputStreamEntity(input, length);
    e.setContentType(contentType);
    e.setContentEncoding("UTF-8");
    try {
        execHttpPut(url, e, httpClient, httpContext, authenticator);
    } finally {
        closeEntity(e);
    }
}

From source file:project.cs.netinfservice.netinf.node.resolution.NameResolutionService.java

/**
 * Creates an HTTP Post request to get an IO from the NRS.
 *
 * @param uri/*from  w w  w .ja  va 2  s.c  om*/
 *      The NetInf format URI for getting IOs
 * @return
 *      The HTTP Post request
 * @throws UnsupportedEncodingException
 *      In case UTF-8 is not supported
 */
private HttpPost createGet(String uri) throws UnsupportedEncodingException {
    // Create a new post, with url = http://host:port/netinfproto/get
    HttpPost post = new HttpPost(HTTP + getHost() + ":" + getPort() + "/netinfproto/get");

    // Get message id and ext
    String msgid = Integer.toString(mRandomGenerator.nextInt(MSG_ID_MAX));
    String ext = "no extension";

    // Finishes the URI
    String completeUri = "URI=" + uri + "&msgid=" + msgid + "&ext=" + ext;

    // TODO: Check if this is really necessary.
    // Encodes the URL
    String encodeUrl = null;

    encodeUrl = URLEncoder.encode(completeUri, "UTF-8");

    // New HTTP entity
    HttpEntity newEntity = new InputStreamEntity(fromString(encodeUrl), encodeUrl.getBytes().length);

    // Add header to the HTTP Entity
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");
    post.setEntity(newEntity);

    // Return HTTP post created
    return post;
}

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

/**Uploads the data, returns the HTTP result code*/
public int performUpload(HttpConnectionParameter connectionParameter, AS2Message message, Partner sender,
        Partner receiver, URL receiptURL) {
    String ediintFeatures = "multiple-attachments, CEM";
    //set the http connection/routing/protocol parameter
    HttpParams httpParams = new BasicHttpParams();
    if (connectionParameter.getConnectionTimeoutMillis() != -1) {
        HttpConnectionParams.setConnectionTimeout(httpParams, connectionParameter.getConnectionTimeoutMillis());
    }/* w ww.ja  v  a 2s  . c o m*/
    if (connectionParameter.getSoTimeoutMillis() != -1) {
        HttpConnectionParams.setSoTimeout(httpParams, connectionParameter.getSoTimeoutMillis());
    }
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, connectionParameter.isStaleConnectionCheck());
    if (connectionParameter.getHttpProtocolVersion() == null) {
        //default settings: HTTP 1.1
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_0)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_0);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_1)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    }
    HttpProtocolParams.setUseExpectContinue(httpParams, connectionParameter.isUseExpectContinue());
    HttpProtocolParams.setUserAgent(httpParams, connectionParameter.getUserAgent());
    if (connectionParameter.getLocalAddress() != null) {
        ConnRouteParams.setLocalAddress(httpParams, connectionParameter.getLocalAddress());
    }
    int status = -1;
    HttpPost filePost = null;
    DefaultHttpClient httpClient = null;
    try {
        ClientConnectionManager clientConnectionManager = this.createClientConnectionManager(httpParams);
        httpClient = new DefaultHttpClient(clientConnectionManager, httpParams);
        //some ssl implementations have problems with a session/connection reuse
        httpClient.setReuseStrategy(new NoConnectionReuseStrategy());
        //disable SSL hostname verification. Do not confuse this with SSL trust verification!
        SSLSocketFactory sslFactory = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry()
                .get("https").getSocketFactory();
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        //determine the receipt URL if it is not set
        if (receiptURL == null) {
            //async MDN requested?
            if (message.isMDN()) {
                if (this.runtimeConnection == null) {
                    throw new IllegalArgumentException(
                            "MessageHTTPUploader.performUpload(): A MDN receipt URL is not set, unable to determine where to send the MDN");
                }
                MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection,
                        this.runtimeConnection);
                AS2MessageInfo relatedMessageInfo = messageAccess
                        .getLastMessageEntry(((AS2MDNInfo) message.getAS2Info()).getRelatedMessageId());
                receiptURL = new URL(relatedMessageInfo.getAsyncMDNURL());
            } else {
                receiptURL = new URL(receiver.getURL());
            }
        }
        filePost = new HttpPost(receiptURL.toExternalForm());
        filePost.addHeader("as2-version", "1.2");
        filePost.addHeader("ediint-features", ediintFeatures);
        filePost.addHeader("mime-version", "1.0");
        filePost.addHeader("recipient-address", receiptURL.toExternalForm());
        filePost.addHeader("message-id", "<" + message.getAS2Info().getMessageId() + ">");
        filePost.addHeader("as2-from", AS2Message.escapeFromToHeader(sender.getAS2Identification()));
        filePost.addHeader("as2-to", AS2Message.escapeFromToHeader(receiver.getAS2Identification()));
        String originalFilename = null;
        if (message.getPayloads() != null && message.getPayloads().size() > 0) {
            originalFilename = message.getPayloads().get(0).getOriginalFilename();
        }
        if (originalFilename != null) {
            String subject = this.replace(message.getAS2Info().getSubject(), "${filename}", originalFilename);
            filePost.addHeader("subject", subject);
            //update the message infos subject with the actual content
            if (!message.isMDN()) {
                ((AS2MessageInfo) message.getAS2Info()).setSubject(subject);
                //refresh this in the database if it is requested
                if (this.runtimeConnection != null) {
                    MessageAccessDB access = new MessageAccessDB(this.configConnection, this.runtimeConnection);
                    access.updateSubject((AS2MessageInfo) message.getAS2Info());
                }
            }
        } else {
            filePost.addHeader("subject", message.getAS2Info().getSubject());
        }
        filePost.addHeader("from", sender.getEmail());
        filePost.addHeader("connection", "close, TE");
        //the data header must be always in english locale else there would be special
        //french characters (e.g. 13 dc. 2011 16:28:56 CET) which is not allowed after 
        //RFC 4130           
        DateFormat format = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss zz", Locale.US);
        filePost.addHeader("date", format.format(new Date()));
        String contentType = null;
        if (message.getAS2Info().getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            contentType = "application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m";
        } else {
            contentType = message.getContentType();
        }
        filePost.addHeader("content-type", contentType);
        //MDN header, this is always the way for async MDNs
        if (message.isMDN()) {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("sending.mdn.async",
                                new Object[] { message.getAS2Info().getMessageId(), receiptURL }),
                        message.getAS2Info());
            }
            filePost.addHeader("server", message.getAS2Info().getUserAgent());
        } else {
            AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
            //outbound AS2/CEM message
            if (messageInfo.requestsSyncMDN()) {
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    }
                }
            } else {
                //Message with ASYNC MDN request
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    }
                }
                //The following header indicates that this requests an asnc MDN.
                //When the header "receipt-delivery-option" is present,
                //the header "disposition-notification-to" serves as a request
                //for an asynchronous MDN.
                //The header "receipt-delivery-option" must always be accompanied by
                //the header "disposition-notification-to".
                //When the header "receipt-delivery-option" is not present and the header
                //"disposition-notification-to" is present, the header "disposition-notification-to"
                //serves as a request for a synchronous MDN.
                filePost.addHeader("receipt-delivery-option", sender.getMdnURL());
            }
            filePost.addHeader("disposition-notification-to", sender.getMdnURL());
            //request a signed MDN if this is set up in the partner configuration
            if (receiver.isSignedMDN()) {
                filePost.addHeader("disposition-notification-options",
                        messageInfo.getDispositionNotificationOptions().getHeaderValue());
            }
            if (messageInfo.getSignType() != AS2Message.SIGNATURE_NONE) {
                filePost.addHeader("content-disposition", "attachment; filename=\"smime.p7m\"");
            } else if (messageInfo.getSignType() == AS2Message.SIGNATURE_NONE
                    && message.getAS2Info().getSignType() == AS2Message.ENCRYPTION_NONE) {
                filePost.addHeader("content-disposition",
                        "attachment; filename=\"" + message.getPayload(0).getOriginalFilename() + "\"");
            }
        }
        int port = receiptURL.getPort();
        if (port == -1) {
            port = receiptURL.getDefaultPort();
        }
        filePost.addHeader("host", receiptURL.getHost() + ":" + port);
        InputStream rawDataInputStream = message.getRawDataInputStream();
        InputStreamEntity postEntity = new InputStreamEntity(rawDataInputStream, message.getRawDataSize());
        postEntity.setContentType(contentType);
        filePost.setEntity(postEntity);
        if (connectionParameter.getProxy() != null) {
            this.setProxyToConnection(httpClient, message, connectionParameter.getProxy());
        }
        this.setHTTPAuthentication(httpClient, receiver, message.getAS2Info().isMDN());
        this.updateUploadHttpHeader(filePost, receiver);
        HttpHost targetHost = new HttpHost(receiptURL.getHost(), receiptURL.getPort(),
                receiptURL.getProtocol());
        BasicHttpContext localcontext = new BasicHttpContext();
        // Generate BASIC scheme object and stick it to the local
        // execution context. Without this a HTTP authentication will not be sent
        BasicScheme basicAuth = new BasicScheme();
        localcontext.setAttribute("preemptive-auth", basicAuth);
        HttpResponse httpResponse = httpClient.execute(targetHost, filePost, localcontext);
        rawDataInputStream.close();
        this.responseData = this.readEntityData(httpResponse);
        if (httpResponse != null) {
            this.responseStatusLine = httpResponse.getStatusLine();
            status = this.responseStatusLine.getStatusCode();
            this.responseHeader = httpResponse.getAllHeaders();
        }
        for (Header singleHeader : filePost.getAllHeaders()) {
            if (singleHeader.getValue() != null) {
                this.requestHeader.setProperty(singleHeader.getName(), singleHeader.getValue());
            }
        }
        //accept all 2xx answers
        //SC_ACCEPTED Status code (202) indicating that a request was accepted for processing, but was not completed.
        //SC_CREATED  Status code (201) indicating the request succeeded and created a new resource on the server.
        //SC_NO_CONTENT Status code (204) indicating that the request succeeded but that there was no new information to return.
        //SC_NON_AUTHORITATIVE_INFORMATION Status code (203) indicating that the meta information presented by the client did not originate from the server.
        //SC_OK Status code (200) indicating the request succeeded normally.
        //SC_RESET_CONTENT Status code (205) indicating that the agent SHOULD reset the document view which caused the request to be sent.
        //SC_PARTIAL_CONTENT Status code (206) indicating that the server has fulfilled the partial GET request for the resource.
        if (status != HttpServletResponse.SC_OK && status != HttpServletResponse.SC_ACCEPTED
                && status != HttpServletResponse.SC_CREATED && status != HttpServletResponse.SC_NO_CONTENT
                && status != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION
                && status != HttpServletResponse.SC_RESET_CONTENT
                && status != HttpServletResponse.SC_PARTIAL_CONTENT) {
            if (this.logger != null) {
                this.logger
                        .severe(this.rb.getResourceString("error.httpupload",
                                new Object[] { message.getAS2Info().getMessageId(),
                                        URLDecoder.decode(
                                                this.responseStatusLine == null ? ""
                                                        : this.responseStatusLine.getReasonPhrase(),
                                                "UTF-8") }));
            }
        }
    } catch (Exception ex) {
        if (this.logger != null) {
            StringBuilder errorMessage = new StringBuilder(message.getAS2Info().getMessageId());
            errorMessage.append(": MessageHTTPUploader.performUpload: [");
            errorMessage.append(ex.getClass().getSimpleName());
            errorMessage.append("]");
            if (ex.getMessage() != null) {
                errorMessage.append(": ").append(ex.getMessage());
            }
            this.logger.log(Level.SEVERE, errorMessage.toString(), message.getAS2Info());
        }
    } finally {
        if (httpClient != null && httpClient.getConnectionManager() != null) {
            //shutdown the HTTPClient to release the resources
            httpClient.getConnectionManager().shutdown();
        }
    }
    return (status);
}

From source file:org.apache.manifoldcf.agents.output.amazoncloudsearch.AmazonCloudSearchConnector.java

private String postData(InputStream jsonData) throws ServiceInterruption, ManifoldCFException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   ww w  .  j  av a  2s  .c om*/
        BinaryInput bi = new TempFileInput(jsonData);
        try {
            poster.setEntity(new InputStreamEntity(bi.getStream(), bi.getLength()));
            HttpResponse res = httpclient.execute(poster);

            HttpEntity resEntity = res.getEntity();
            return EntityUtils.toString(resEntity);
        } finally {
            bi.discard();
        }
    } catch (ClientProtocolException e) {
        throw new ManifoldCFException(e);
    } catch (IOException e) {
        handleIOException(e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            //do nothing
        }
    }
    return null;
}

From source file:org.esigate.DriverTest.java

/**
 * 0000141: Socket read timeout causes a stacktrace and may leak connection
 * http://www.esigate.org/mantisbt/view.php?id=141
 * //  w w  w.  ja v a 2s . c o  m
 * The warning will not be fixed in HttpClient but the leak is fixed.
 * 
 * @throws Exception
 */
public void testSocketReadTimeoutWithCacheAndGzipDoesNotLeak() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE, "http://localhost/");
    properties.put(Parameters.USE_CACHE, "true");

    BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK,
            "Ok");
    response.addHeader("Date", DateUtils.formatDate(new Date()));
    response.addHeader("Cache-control", "public, max-age=1000");
    response.addHeader("Content-Encoding", "gzip");
    response.setEntity(new InputStreamEntity(new InputStream() {
        @Override
        public int read() throws IOException {
            throw new SocketTimeoutException("Read timed out");
        }
    }, 1000));
    mockConnectionManager.setResponse(response);

    Driver driver = createMockDriver(properties, mockConnectionManager);

    request = TestUtils.createIncomingRequest("http://test.mydomain.fr/");
    request.addHeader("Accept-Encoding", "gzip, deflate");

    try {
        driver.proxy("/", request.build());
        fail("We should have had a SocketTimeoutException");
    } catch (HttpErrorPage e) {
        // That is what we expect
        assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, e.getHttpResponse().getStatusLine().getStatusCode());
    }
    assertFalse("All the connections should have been closed", mockConnectionManager.isOpen());
}

From source file:edu.mit.mobile.android.locast.net.NetworkClient.java

/**
 * Uploads content using HTTP PUT./*from  w  w w  . j  av  a 2 s. c  o m*/
 *
 * @param context
 * @param progressListener
 * @param serverPath
 *            the URL fragment to which the content should be PUT
 * @param localFile
 *            the local file that should be stored on the server
 * @param contentType
 *            MIME type of the file to be uploaded
 * @return
 * @throws NetworkProtocolException
 * @throws IOException
 * @throws JSONException
 * @throws IllegalStateException
 */
public JSONObject uploadContent(Context context, TransferProgressListener progressListener, String serverPath,
        Uri localFile, String contentType)
        throws NetworkProtocolException, IOException, IllegalStateException, JSONException {

    if (localFile == null) {
        throw new IOException("Cannot send. Content item does not reference a local file.");
    }

    final InputStream is = getFileStream(context, localFile);

    // next step is to send the file contents.
    final String putUrl = getFullUrlAsString(serverPath);
    final HttpPut r = new HttpPut(putUrl);

    if (DEBUG) {
        Log.d(TAG, "HTTP PUTting " + localFile + " (mimetype: " + contentType + ") to " + putUrl);
    }

    r.setHeader("Content-Type", contentType);

    final AssetFileDescriptor afd = context.getContentResolver().openAssetFileDescriptor(localFile, "r");

    final InputStreamWatcher isw = new InputStreamWatcher(is, progressListener);

    r.setEntity(new InputStreamEntity(isw, afd.getLength()));

    final HttpResponse c = this.execute(r);
    checkStatusCode(c, true);
    return toJsonObject(c);
}

From source file:jp.mixi.android.sdk.MixiContainerImpl.java

/**
 * HTTP??//  ww w. j av a  2  s.  c o  m
 * 
 * @param endpointPath ?
 * @param stream ?InputStream
 * @param length InputStream??
 * @return HttpUriRequest
 */
private HttpUriRequest getHttpMethod(String endpointPath, String contentType, HttpMethod method,
        InputStream stream, long length) throws IOException {

    InputStreamEntity entity = new InputStreamEntity(stream, length);
    entity.setContentType(contentType);
    switch (method) {
    case POST:
        HttpPost postMethod = new HttpPost(Constants.GRAPH_BASE_URL + endpointPath);
        postMethod.setEntity(entity);
        return postMethod;
    case PUT:
        HttpPut putMethod = new HttpPut(Constants.GRAPH_BASE_URL + endpointPath);
        putMethod.setEntity(entity);
        return putMethod;

    default:
        Log.e(TAG, "Unsupported http method");
        throw new IllegalArgumentException("Unsupported HttpMethod parameter:" + method);
    }

}

From source file:org.jets3t.service.impl.rest.httpclient.RestS3Service.java

@Override
protected MultipartPart multipartUploadPartImpl(String uploadId, String bucketName, Integer partNumber,
        SS3Object object) throws S3ServiceException {
    Map<String, String> requestParameters = new HashMap<String, String>();
    requestParameters.put("uploadId", uploadId);
    requestParameters.put("partNumber", "" + partNumber);

    // Remove all non-HTTP headers from object metadata for multipart part uploads
    synchronized (object) { // Thread-safe header handling.
        List<String> metadataNamesToRemove = new ArrayList<String>();
        for (String name : object.getMetadataMap().keySet()) {
            if (!RestUtils.HTTP_HEADER_METADATA_NAMES.contains(name.toLowerCase())) {
                // Actual metadata name in object does not include the prefix
                metadataNamesToRemove.add(name);
            }/* w  w w.j  a va2 s .  co  m*/
        }
        for (String name : metadataNamesToRemove) {
            object.removeMetadata(name);
        }
    }

    try {
        // Always disable live MD5 hash check for MultiPart Part uploads, since the ETag
        // hash value returned by S3 is not an MD5 hash of the uploaded data anyway (Issue #141).
        boolean isLiveMD5HashingRequired = false;

        HttpEntity requestEntity = null;
        if (object.getDataInputStream() != null) {
            if (object.containsMetadata(StorageObject.METADATA_HEADER_CONTENT_LENGTH)) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Uploading multipart part data with Content-Length: " + object.getContentLength());
                }
                requestEntity = new RepeatableRequestEntity(object.getKey(), object.getDataInputStream(),
                        object.getContentType(), object.getContentLength(), this.jets3tProperties,
                        isLiveMD5HashingRequired);
            } else {
                // Use InputStreamRequestEntity for objects with an unknown content length, as the
                // entity will cache the results and doesn't need to know the data length in advance.
                if (log.isWarnEnabled()) {
                    log.warn("Content-Length of multipart part stream not set, "
                            + "will automatically determine data length in memory");
                }
                requestEntity = new InputStreamEntity(object.getDataInputStream(), -1);
            }
        }

        // Override any storage class with an empty value, which means don't apply one (Issue #121)
        object.setStorageClass("");
        this.putObjectWithRequestEntityImpl(bucketName, object, requestEntity, requestParameters);

        // Populate part with response data that is accessible via the object's metadata
        MultipartPart part = new MultipartPart(partNumber, object.getLastModifiedDate(), object.getETag(),
                object.getContentLength());
        return part;
    } catch (ServiceException se) {
        throw new S3ServiceException(se);
    }
}

From source file:org.olat.core.commons.services.webdav.WebDAVCommandsTest.java

@Test
public void customizingFolder() throws IOException, URISyntaxException {
    Identity admin = JunitTestHelper.createAndPersistIdentityAsAdmin("admin-webdav");
    dbInstance.commitAndCloseSession();//from w  w w . ja  v a  2 s.c  o m

    WebDAVConnection conn = new WebDAVConnection();
    conn.setCredentials(admin.getName(), "A6B7C8");

    //Has access?
    URI customizingUri = conn.getBaseURI().path("webdav").path("customizing").build();
    String customizingXml = conn.propfind(customizingUri, 2);
    Assert.assertTrue(customizingXml.contains("<D:href>/webdav/customizing/</D:href>"));

    //PUT in the folder
    String randomFilename = "infos" + UUID.randomUUID() + ".txt";
    URI textUri = conn.getBaseURI().path("webdav").path("customizing").path(randomFilename).build();
    HttpPut put = conn.createPut(textUri);
    InputStream dataStream = WebDAVCommandsTest.class.getResourceAsStream("text.txt");
    InputStreamEntity entity = new InputStreamEntity(dataStream, -1);
    put.setEntity(entity);
    HttpResponse putResponse = conn.execute(put);
    Assert.assertEquals(201, putResponse.getStatusLine().getStatusCode());

    //GET
    HttpGet get = conn.createGet(textUri);
    HttpResponse getResponse = conn.execute(get);
    Assert.assertEquals(200, getResponse.getStatusLine().getStatusCode());
    String text = EntityUtils.toString(getResponse.getEntity());
    Assert.assertEquals("Small text", text);

    conn.close();
}

From source file:org.georchestra.security.Proxy.java

private HttpRequestBase makeRequest(HttpServletRequest request, RequestType requestType, String sURL)
        throws IOException {
    HttpRequestBase targetRequest;//  w ww .  j  av  a2 s  .  c  om
    try {
        // Split URL
        URL url = new URL(sURL);
        URI uri = buildUri(url);

        switch (requestType) {
        case GET: {
            logger.debug("New request is: " + sURL + "\nRequest is GET");

            HttpGet get = new HttpGet(uri);
            targetRequest = get;
            break;
        }
        case POST: {
            logger.debug("New request is: " + sURL + "\nRequest is POST");

            HttpPost post = new HttpPost(uri);
            HttpEntity entity;
            request.setCharacterEncoding("UTF8");
            if (isFormContentType(request)) {
                logger.debug("Post is recognized as a form post.");
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
                    String name = (String) e.nextElement();
                    String[] v = request.getParameterValues(name);
                    for (String value : v) {
                        NameValuePair nv = new BasicNameValuePair(name, value);
                        parameters.add(nv);
                    }
                }
                String charset = request.getCharacterEncoding();
                try {
                    Charset.forName(charset);
                } catch (Throwable t) {
                    charset = null;
                }
                if (charset == null) {
                    charset = defaultCharset;
                }
                entity = new UrlEncodedFormEntity(parameters, charset);
                post.setEntity(entity);

            } else {
                logger.debug("Post is NOT recognized as a form post. (Not an error, just a comment)");
                int contentLength = request.getContentLength();
                ServletInputStream inputStream = request.getInputStream();
                entity = new InputStreamEntity(inputStream, contentLength);
            }
            post.setEntity(entity);
            targetRequest = post;
            break;
        }
        case TRACE: {
            logger.debug("New request is: " + sURL + "\nRequest is TRACE");

            HttpTrace post = new HttpTrace(uri);

            targetRequest = post;
            break;
        }
        case OPTIONS: {
            logger.debug("New request is: " + sURL + "\nRequest is OPTIONS");

            HttpOptions post = new HttpOptions(uri);

            targetRequest = post;
            break;
        }
        case HEAD: {
            logger.debug("New request is: " + sURL + "\nRequest is HEAD");

            HttpHead post = new HttpHead(uri);

            targetRequest = post;
            break;
        }
        case PUT: {
            logger.debug("New request is: " + sURL + "\nRequest is PUT");

            HttpPut put = new HttpPut(uri);

            put.setEntity(new InputStreamEntity(request.getInputStream(), request.getContentLength()));

            targetRequest = put;
            break;
        }
        case DELETE: {
            logger.debug("New request is: " + sURL + "\nRequest is DELETE");

            HttpDelete delete = new HttpDelete(uri);

            targetRequest = delete;
            break;
        }
        default: {
            String msg = requestType + " not yet supported";
            logger.error(msg);
            throw new IllegalArgumentException(msg);
        }

        }
    } catch (URISyntaxException e) {
        logger.error("ERROR creating URI from " + sURL, e);
        throw new IOException(e);
    }

    return targetRequest;
}