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();
}
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);
}
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);
}
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;
}
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());
}
Aggregations