Search in sources :

Example 26 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project jmeter by apache.

the class HTTPHC4Impl method setupHttpEntityEnclosingRequestData.

/**
 * @param entityEnclosingRequest {@link HttpEntityEnclosingRequestBase}
 * @return String body sent if computable
 * @throws IOException if sending the data fails due to I/O
 */
protected String setupHttpEntityEnclosingRequestData(HttpEntityEnclosingRequestBase entityEnclosingRequest) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    HTTPFileArg[] files = getHTTPFiles();
    final String contentEncoding = getContentEncodingOrNull();
    final boolean haveContentEncoding = contentEncoding != null;
    // application/x-www-form-urlencoded post request
    if (getUseMultipart()) {
        if (entityEnclosingRequest.getHeaders(HTTPConstants.HEADER_CONTENT_TYPE).length > 0) {
            log.info("Content-Header is set already on the request! Will be replaced by a Multipart-Header. Old headers: {}", Arrays.asList(entityEnclosingRequest.getHeaders(HTTPConstants.HEADER_CONTENT_TYPE)));
            entityEnclosingRequest.removeHeaders(HTTPConstants.HEADER_CONTENT_TYPE);
        }
        // If a content encoding is specified, we use that as the
        // encoding of any parameter values
        Charset charset;
        if (haveContentEncoding) {
            charset = Charset.forName(contentEncoding);
        } else {
            charset = MIME.DEFAULT_CHARSET;
        }
        if (log.isDebugEnabled()) {
            log.debug("Building multipart with:getDoBrowserCompatibleMultipart(): {}, with charset:{}, haveContentEncoding:{}", getDoBrowserCompatibleMultipart(), charset, haveContentEncoding);
        }
        // Write the request to our own stream
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (getDoBrowserCompatibleMultipart()) {
            multipartEntityBuilder.setLaxMode();
        } else {
            multipartEntityBuilder.setStrictMode();
        }
        // Add any parameters
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            ContentType contentType;
            if (arg.getContentType().indexOf(';') >= 0) {
                // assume, that the content type contains charset info
                // don't add another charset and use parse to cope with the semicolon
                contentType = ContentType.parse(arg.getContentType());
            } else {
                contentType = ContentType.create(arg.getContentType(), charset);
            }
            StringBody stringBody = new StringBody(arg.getValue(), contentType);
            FormBodyPart formPart = FormBodyPartBuilder.create(parameterName, stringBody).build();
            multipartEntityBuilder.addPart(formPart);
        }
        // Add any files
        // Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
        ViewableFileBody[] fileBodies = new ViewableFileBody[files.length];
        for (int i = 0; i < files.length; i++) {
            HTTPFileArg file = files[i];
            File reservedFile = FileServer.getFileServer().getResolvedFile(file.getPath());
            fileBodies[i] = new ViewableFileBody(reservedFile, ContentType.parse(file.getMimeType()));
            multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i]);
        }
        HttpEntity entity = multipartEntityBuilder.build();
        entityEnclosingRequest.setEntity(entity);
        writeEntityToSB(postedBody, entity, fileBodies, contentEncoding);
    } else {
        // not multipart
        // Check if the header manager had a content type header
        // This allows the user to specify their own content-type for a POST request
        Header contentTypeHeader = entityEnclosingRequest.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null && contentTypeHeader.getValue().length() > 0;
        // TODO: needs a multiple file upload scenario
        if (!hasArguments() && getSendFileAsPostBody()) {
            // If getSendFileAsPostBody returned true, it's sure that file is not null
            HTTPFileArg file = files[0];
            if (!hasContentTypeHeader) {
                // Allow the mimetype of the file to control the content type
                if (file.getMimeType() != null && file.getMimeType().length() > 0) {
                    entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                } else if (ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
                    entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
            }
            FileEntity fileRequestEntity = new FileEntity(FileServer.getFileServer().getResolvedFile(file.getPath()), (ContentType) null);
            entityEnclosingRequest.setEntity(fileRequestEntity);
            // We just add placeholder text for file content
            postedBody.append("<actual file content, not shown here>");
        } else {
            // just send all the values as the post body
            if (getSendParameterValuesAsPostBody()) {
                // TODO: needs a multiple file upload scenario
                if (!hasContentTypeHeader) {
                    HTTPFileArg file = files.length > 0 ? files[0] : null;
                    if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                        entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                    } else if (ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
                        entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                    }
                }
                // Just append all the parameter values, and use that as the post body
                StringBuilder postBody = new StringBuilder();
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    // Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
                    if (haveContentEncoding) {
                        postBody.append(arg.getEncodedValue(contentEncoding));
                    } else {
                        postBody.append(arg.getEncodedValue());
                    }
                }
                // Let StringEntity perform the encoding
                StringEntity requestEntity = new StringEntity(postBody.toString(), contentEncoding);
                entityEnclosingRequest.setEntity(requestEntity);
                postedBody.append(postBody.toString());
            } else {
                // Set the content type
                if (!hasContentTypeHeader && ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
                    entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
                String urlContentEncoding = contentEncoding;
                UrlEncodedFormEntity entity = createUrlEncodedFormEntity(urlContentEncoding);
                entityEnclosingRequest.setEntity(entity);
                writeEntityToSB(postedBody, entity, EMPTY_FILE_BODIES, contentEncoding);
            }
        }
    }
    return postedBody.toString();
}
Also used : FileEntity(org.apache.http.entity.FileEntity) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) JMeterProperty(org.apache.jmeter.testelement.property.JMeterProperty) ContentType(org.apache.http.entity.ContentType) HttpEntity(org.apache.http.HttpEntity) Charset(java.nio.charset.Charset) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) HTTPFileArg(org.apache.jmeter.protocol.http.util.HTTPFileArg) FormBodyPart(org.apache.http.entity.mime.FormBodyPart) StringEntity(org.apache.http.entity.StringEntity) HTTPArgument(org.apache.jmeter.protocol.http.util.HTTPArgument) Header(org.apache.http.Header) BufferedHeader(org.apache.http.message.BufferedHeader) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File)

Example 27 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project nanohttpd by NanoHttpd.

the class GetAndPostIntegrationTest method testPostRequestWithMultipartExtremEncodedParameters.

@Test
public void testPostRequestWithMultipartExtremEncodedParameters() throws Exception {
    this.testServer.response = "testPostRequestWithMultipartEncodedParameters";
    HttpPost httppost = new HttpPost("http://localhost:8192/chin");
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "sfsadfasdf", Charset.forName("UTF-8"));
    reqEntity.addPart("specialString", new StringBody("拖拉图片到浏览器,可以实现预览功能", "text/plain", Charset.forName("UTF-8")));
    reqEntity.addPart("gender", new StringBody("图片名称", Charset.forName("UTF-8")) {

        @Override
        public String getFilename() {
            return "图片名称";
        }
    });
    httppost.setEntity(reqEntity);
    HttpResponse response = this.httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    String responseBody = EntityUtils.toString(entity, "UTF-8");
    assertEquals("POST:testPostRequestWithMultipartEncodedParameters-params=2;gender=图片名称;specialString=拖拉图片到浏览器,可以实现预览功能", responseBody);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) HttpResponse(org.apache.http.HttpResponse) Test(org.junit.Test)

Example 28 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project nanohttpd by NanoHttpd.

the class GetAndPostIntegrationTest method testPostRequestWithMultipartEncodedParameters.

@Test
public void testPostRequestWithMultipartEncodedParameters() throws Exception {
    this.testServer.response = "testPostRequestWithMultipartEncodedParameters";
    HttpPost httppost = new HttpPost("http://localhost:8192/");
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("age", new StringBody("120"));
    reqEntity.addPart("gender", new StringBody("Male"));
    httppost.setEntity(reqEntity);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = this.httpclient.execute(httppost, responseHandler);
    assertEquals("POST:testPostRequestWithMultipartEncodedParameters-params=2;age=120;gender=Male", responseBody);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) Test(org.junit.Test)

Example 29 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project Talon-for-Twitter by klinker24.

the class TwitPicHelper method uploadToTwitPic.

private TwitPicStatus uploadToTwitPic() {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(POST_URL);
        post.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER);
        post.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter));
        if (file == null) {
            // only the input stream was sent, so we need to convert it to a file
            Log.v("talon_twitpic", "converting to file from input stream");
            String filePath = saveStreamTemp(stream);
            file = new File(filePath);
        } else {
            Log.v("talon_twitpic", "already have the file, going right to send it");
        }
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("key", new StringBody(TWITPIC_API_KEY));
        entity.addPart("media", new FileBody(file));
        entity.addPart("message", new StringBody(message));
        Log.v("talon_twitpic", "uploading now");
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        String url = "";
        StringBuilder builder = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            Log.v("talon_twitpic", line);
            builder.append(line);
        }
        try {
            // there is only going to be one thing returned ever
            JSONObject jsonObject = new JSONObject(builder.toString());
            url = jsonObject.getString("url");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.v("talon_twitpic", "url: " + url);
        Log.v("talon_twitpic", "message: " + message);
        return new TwitPicStatus(message, url);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) InputStreamReader(java.io.InputStreamReader) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) JSONObject(org.json.JSONObject) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader) File(java.io.File)

Example 30 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project nanohttpd by NanoHttpd.

the class TestNanoFileUpLoad method executeUpload.

private void executeUpload(CloseableHttpClient httpclient, String textFileName, HttpPost post) throws IOException, ClientProtocolException {
    FileBody fileBody = new FileBody(new File(textFileName), ContentType.DEFAULT_BINARY);
    StringBody stringBody1 = new StringBody("Message 1", ContentType.MULTIPART_FORM_DATA);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    builder.addPart("text1", stringBody1);
    HttpEntity entity = builder.build();
    // 
    post.setEntity(entity);
    HttpResponse response = httpclient.execute(post);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
}
Also used : MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) StringBody(org.apache.http.entity.mime.content.StringBody) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(org.apache.http.HttpResponse) File(java.io.File)

Aggregations

StringBody (org.apache.http.entity.mime.content.StringBody)65 HttpPost (org.apache.http.client.methods.HttpPost)44 MultipartEntity (org.apache.http.entity.mime.MultipartEntity)40 FileBody (org.apache.http.entity.mime.content.FileBody)30 HttpResponse (org.apache.http.HttpResponse)29 File (java.io.File)25 Test (org.junit.Test)25 HttpEntity (org.apache.http.HttpEntity)21 IOException (java.io.IOException)15 MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)15 TestHttpClient (io.undertow.testutils.TestHttpClient)14 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)8 Header (org.apache.http.Header)6 HttpClient (org.apache.http.client.HttpClient)6 FormBodyPart (org.apache.http.entity.mime.FormBodyPart)6 HashMap (java.util.HashMap)5 Map (java.util.Map)5 InputStreamBody (org.apache.http.entity.mime.content.InputStreamBody)5 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)5 RequestBuilder (org.apache.sling.testing.tools.http.RequestBuilder)5