Java Code Examples for org.apache.http.entity.ContentType#MULTIPART_FORM_DATA

The following examples show how to use org.apache.http.entity.ContentType#MULTIPART_FORM_DATA . 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: WS.java    From candybean with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Private helper method to abstract creating a POST/PUT request.
 * Side Effect: Adds the body to the request
 *
 * @param request     A PUT or POST request
 * @param body        Map of Key Value pairs
 * @param contentType The intended content type of the body
 */
protected static void addBodyToRequest(HttpEntityEnclosingRequestBase request, Map<String, Object> body, ContentType contentType) {
	if (body != null) {
		if (contentType == ContentType.MULTIPART_FORM_DATA) {
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			for (Map.Entry<String, Object> entry : body.entrySet()) {
				builder.addTextBody(entry.getKey(), (String) entry.getValue());
			}
			request.setEntity(builder.build());
		} else {
			JSONObject jsonBody = new JSONObject(body);
			StringEntity strBody = new StringEntity(jsonBody.toJSONString(), ContentType.APPLICATION_JSON);
			request.setEntity(strBody);
		}
	}
}
 
Example 2
Source File: RESTRouteBuilderPOSTFileClientTests.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Test
public void stringPOSTResponseWithParameter()
    throws InterruptedException, ExecutionException, IOException {
  File file = new File(getClass().getClassLoader().getResource("payload.xml").getFile());
  HttpPost post =
      new HttpPost("http://" + HOST + ":" + PORT + SERVICE_REST_GET + "/simpleFilePOSTupload");
  HttpClient client = HttpClientBuilder.create().build();

  FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
  StringBody stringBody1 = new StringBody("bar", ContentType.MULTIPART_FORM_DATA);
  StringBody stringBody2 = new StringBody("world", ContentType.MULTIPART_FORM_DATA);
  //
  MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  builder.addPart("file", fileBody);
  builder.addPart("foo", stringBody1);
  builder.addPart("hello", stringBody2);
  HttpEntity entity = builder.build();
  //
  post.setEntity(entity);
  HttpResponse response = client.execute(post);

  // Use createResponse object to verify upload success
  final String entity1 = convertStreamToString(response.getEntity().getContent());
  System.out.println("-->" + entity1);
  assertTrue(entity1.equals("barworlddfgdfg"));

  testComplete();
}
 
Example 3
Source File: RESTJerseyPOSTFileClientTests.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Test
public void stringPOSTResponseWithParameter()
    throws InterruptedException, ExecutionException, IOException {
  File file = new File(getClass().getClassLoader().getResource("payload.xml").getFile());
  HttpPost post =
      new HttpPost("http://" + HOST + ":" + PORT + SERVICE_REST_GET + "/simpleFilePOSTupload");
  HttpClient client = HttpClientBuilder.create().build();

  FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
  StringBody stringBody1 = new StringBody("bar", ContentType.MULTIPART_FORM_DATA);
  StringBody stringBody2 = new StringBody("world", ContentType.MULTIPART_FORM_DATA);
  //
  MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  builder.addPart("file", fileBody);
  builder.addPart("foo", stringBody1);
  builder.addPart("hello", stringBody2);
  HttpEntity entity = builder.build();
  //
  post.setEntity(entity);
  HttpResponse response = client.execute(post);

  // Use createResponse object to verify upload success
  final String entity1 = convertStreamToString(response.getEntity().getContent());
  System.out.println("-->" + entity1);
  assertTrue(entity1.equals("barworlddfgdfg"));

  testComplete();
}
 
Example 4
Source File: UploadAPITest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
private String upload(String filename) throws Exception {
    InputStream logoStream = UploadAPITest.class.getResourceAsStream("/" + filename);

    HttpPost post = new HttpPost("http://localhost:" + properties.getHttpPort() + "/upload");
    ContentBody fileBody = new InputStreamBody(logoStream, ContentType.APPLICATION_OCTET_STREAM, filename);
    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);

    String staticPath;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        staticPath = TestUtil.consumeText(response);

        assertNotNull(staticPath);
        assertTrue(staticPath.startsWith("/static"));
        assertTrue(staticPath.endsWith("bin"));
    }

    return staticPath;
}
 
Example 5
Source File: HttpClientMultipartLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
    final URL url = Thread.currentThread()
      .getContextClassLoader()
      .getResource("uploads/" + TEXTFILENAME);

    final File file = new File(url.getPath());
    final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    final StringBody stringBody1 = new StringBody("This is message 1", ContentType.MULTIPART_FORM_DATA);
    final StringBody stringBody2 = new StringBody("This is message 2", ContentType.MULTIPART_FORM_DATA);
    //
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("file", fileBody);
    builder.addPart("text1", stringBody1);
    builder.addPart("text2", stringBody2);
    final HttpEntity entity = builder.build();
    //
    post.setEntity(entity);
    response = client.execute(post);

    final int statusCode = response.getStatusLine()
      .getStatusCode();
    final String responseString = getContent();
    final String contentTypeInHeader = getContentTypeHeader();
    assertThat(statusCode, equalTo(HttpStatus.SC_OK));
    // assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
    assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
    System.out.println(responseString);
    System.out.println("POST Content Type: " + contentTypeInHeader);
}
 
Example 6
Source File: FbBotMillNetworkController.java    From fb-botmill with MIT License 4 votes vote down vote up
/**
 * POSTs a message as a JSON string to Facebook.
 *
 * @param recipient
 *            the recipient
 * @param type
 *            the type
 * @param file
 *            the file
 */
public static void postFormDataMessage(String recipient,
		AttachmentType type, File file) {
	String pageToken = FbBotMillContext.getInstance().getPageToken();
	// If the page token is invalid, returns.
	if (!validatePageToken(pageToken)) {
		return;
	}

	// TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO)
	HttpPost post = new HttpPost(
			FbBotMillNetworkConstants.FACEBOOK_BASE_URL
					+ FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL
					+ pageToken);

	FileBody filedata = new FileBody(file);
	StringBody recipientPart = new StringBody("{\"id\":\"" + recipient
			+ "\"}", ContentType.MULTIPART_FORM_DATA);
	StringBody messagePart = new StringBody("{\"attachment\":{\"type\":\""
			+ type.name().toLowerCase() + "\", \"payload\":{}}}",
			ContentType.MULTIPART_FORM_DATA);
	MultipartEntityBuilder builder = MultipartEntityBuilder.create();
	builder.setMode(HttpMultipartMode.STRICT);
	builder.addPart("recipient", recipientPart);
	builder.addPart("message", messagePart);
	// builder.addPart("filedata", filedata);
	builder.addBinaryBody("filedata", file);
	builder.setContentType(ContentType.MULTIPART_FORM_DATA);

	// builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
	HttpEntity entity = builder.build();
	post.setEntity(entity);

	// Logs the raw JSON for debug purposes.
	BufferedReader br;
	// post.addHeader("Content-Type", "multipart/form-data");
	try {
		// br = new BufferedReader(new InputStreamReader(
		// ())));

		Header[] allHeaders = post.getAllHeaders();
		for (Header h : allHeaders) {

			logger.debug("Header {} ->  {}", h.getName(), h.getValue());
		}
		// String output = br.readLine();

	} catch (Exception e) {
		e.printStackTrace();
	}

	// postInternal(post);
}
 
Example 7
Source File: WxMediaService.java    From WeixinMultiPlatform with Apache License 2.0 4 votes vote down vote up
public WxBaseItemMediaEntity remoteMediaUpload(String accessToken,
		WxMediaTypeEnum type, byte[] content) throws WxException {
	MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
	String typeString = null;
	switch (type) {
	case IMAGE:
	case THUMB:
	case VIDEO:
	case VOICE:
		typeString = type.toString().toLowerCase();
		break;
	case MUSIC:
	case DEFAULT:
	case PIC_DESC:
		throw new WxException("Not supported upload type : "
				+ type.toString());
	default:
		break;
	}

	Map<String, String> params = WxUtil.getAccessTokenParams(accessToken);
	System.out.println(typeString);
	params.put("type", typeString);
	ContentBody contentBody = new ByteArrayBody(content, ContentType.MULTIPART_FORM_DATA, "name.jpg");
	entityBuilder.addPart("media", contentBody);
	MediaResultMapper result = WxUtil.sendRequest(
			config.getMediaUploadUrl(), HttpMethod.POST, params,
			entityBuilder.build(), MediaResultMapper.class);

	WxBaseItemMediaEntity resultEntity = null;
	switch (type) {
	case IMAGE:
		WxItemImageEntity imageEntity = new WxItemImageEntity();
		imageEntity.setMediaId(result.getMedia_id());
		imageEntity.setCreatedDate(new Date(result.getCreated_at() * 1000));
		resultEntity = imageEntity;
		break;
	case THUMB:
		WxItemThumbEntity thumbEntity = new WxItemThumbEntity();
		thumbEntity.setMediaId(result.getMedia_id());
		thumbEntity.setCreatedDate(new Date(result.getCreated_at() * 1000));
		resultEntity = thumbEntity;
		break;
	case VIDEO:
		WxItemVideoEntity videoEntity = new WxItemVideoEntity();
		videoEntity.setMediaId(result.getMedia_id());
		videoEntity.setCreatedDate(new Date(result.getCreated_at() * 1000));
		resultEntity = videoEntity;
		break;
	case VOICE:
		WxItemVoiceEntity voiceEntity = new WxItemVoiceEntity();
		voiceEntity.setMediaId(result.getMedia_id());
		voiceEntity.setCreatedDate(new Date(result.getCreated_at() * 1000));
		resultEntity = voiceEntity;
		break;
	case MUSIC:
	case DEFAULT:
	case PIC_DESC:
		throw new WxException("Not supported upload type : "
				+ type.toString());
	default:
		break;
	}
	return resultEntity;
}