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

The following examples show how to use org.apache.http.entity.ContentType#DEFAULT_BINARY . 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: HttpTransport.java    From bender with Apache License 2.0 6 votes vote down vote up
protected HttpResponse sendBatchCompressed(HttpPost httpPost, byte[] raw)
    throws TransportException {
  /*
   * Write gzip data to Entity and set content encoding to gzip
   */
  ByteArrayEntity entity = new ByteArrayEntity(raw, ContentType.DEFAULT_BINARY);
  entity.setContentEncoding("gzip");

  httpPost.addHeader(new BasicHeader("Accept-Encoding", "gzip"));
  httpPost.setEntity(entity);

  /*
   * Make call
   */
  HttpResponse resp = null;
  try {
    resp = this.client.execute(httpPost);
  } catch (IOException e) {
    throw new TransportException("failed to make call", e);
  }

  return resp;
}
 
Example 2
Source File: HttpUploader.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
private URI uploadPackageAndGetURI(final CloseableHttpClient httpclient)
    throws IOException, URISyntaxException {
  File file = new File(this.topologyPackageLocation);
  String uploaderUri = HttpUploaderContext.getHeronUploaderHttpUri(this.config);
  post = new HttpPost(uploaderUri);
  FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
  MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  builder.addPart(FILE, fileBody);
  HttpEntity entity = builder.build();
  post.setEntity(entity);
  HttpResponse response = execute(httpclient);
  String responseString = EntityUtils.toString(response.getEntity(),
      StandardCharsets.UTF_8.name());
  LOG.fine("Topology package download URI: " + responseString);

  return new URI(responseString);
}
 
Example 3
Source File: HttpServerTest.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormParamWithFile() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/testFormParamWithFile", HttpMethod.POST);
    File file = new File(Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").toURI());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    builder.addPart("form", fileBody);
    HttpEntity build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, file.getName());
}
 
Example 4
Source File: CrashReportTask.java    From archivo with GNU General Public License v3.0 6 votes vote down vote up
private void performUpload() {
    Path gzLog = compressLog();
    try (CloseableHttpClient client = buildHttpClient()) {
        HttpPost post = new HttpPost(CRASH_REPORT_URL);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody logFile = new FileBody(gzLog.toFile(), ContentType.DEFAULT_BINARY);
        builder.addPart("log", logFile);
        StringBody uid = new StringBody(userId, ContentType.TEXT_PLAIN);
        builder.addPart("uid", uid);
        HttpEntity postEntity = builder.build();
        post.setEntity(postEntity);
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            logger.debug("Error uploading crash report: {}", response.getStatusLine());
        }
    } catch (IOException e) {
        logger.error("Error uploading crash report: {}", e.getLocalizedMessage());
    }
}
 
Example 5
Source File: RandomTestMocks.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
public HttpResponse(final int maxNumberOfHeaders, final int maxLenghtOfHeader, final int maxLengthOfBody, final int pos) {
	this.statusLine = new BasicStatusLine(PROTOCOL_VERSION, 200, "OK");
	Header[] headers = randomHeaders(maxNumberOfHeaders, maxLenghtOfHeader);
	headers[RNG.nextInt(headers.length)] = new BasicHeader("Position", Integer.toString(pos));
	this.setHeaders(headers);
	this.content = RandomStringUtils.randomAscii(RNG.nextInt(maxLengthOfBody) + 1);
	byte[] body = Util.toByteArray(content);
	this.addHeader("Content-Length", Integer.toString(body.length));
	this.entity = new ByteArrayEntity(body, ContentType.DEFAULT_BINARY);
}
 
Example 6
Source File: RandomTestMocks.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
public HttpResponse(final int maxNumberOfHeaders, final int maxLenghtOfHeader, String passedBody, final int pos) {
	this.statusLine = new BasicStatusLine(PROTOCOL_VERSION, 200, "OK");
	Header[] headers = randomHeaders(maxNumberOfHeaders, maxLenghtOfHeader);
	headers[RNG.nextInt(headers.length)] = new BasicHeader("Position", Integer.toString(pos));
	this.setHeaders(headers);
	this.content = passedBody;
	byte[] body = Util.toByteArray(content);
	this.addHeader("Content-Length", Integer.toString(body.length));
	this.entity = new ByteArrayEntity(body, ContentType.DEFAULT_BINARY);
}
 
Example 7
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 8
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 9
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 10
Source File: RpcxHttpClient.java    From rpcx-java with Apache License 2.0 4 votes vote down vote up
/**
 * http 调用
 *
 * @param url
 * @param service
 * @param method
 * @param params  key=类型  value=json后的值
 * @return
 */
public static String execute(String url, String service, String method, Pair<String, String>... params) {
    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setSocketTimeout(1000)
            .setConnectTimeout(1000)
            .setConnectionRequestTimeout(1000)
            .build();

    try (CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build()) {
        HttpPost post = new HttpPost(url);
        post.setHeader("X-RPCX-ServicePath", service);
        post.setHeader("X-RPCX-ServiceMethod", method);
        post.setHeader("connection", "close");

        Gson gson = new Gson();
        Invocation invocation = new RpcInvocation();
        String[] parameterTypeNames = new String[params.length];
        Object[] arguments = new Object[params.length];
        IntStream.range(0, params.length).forEach(index -> {
            Pair<String, String> p = params[index];
            parameterTypeNames[index] = p.getObject1();
            arguments[index] = p.getObject2();
        });

        invocation.setParameterTypeNames(parameterTypeNames);
        invocation.setArguments(arguments);

        URL u = new URL("rpcx", "", 0);

        ((RpcInvocation) invocation).setClassName(service);
        ((RpcInvocation) invocation).setMethodName(method);

        u.setServiceInterface(invocation.getClassName() + "." + invocation.getMethodName());
        String _params = Stream.of(invocation.getArguments()).map(it -> gson.toJson(it)).collect(Collectors.joining(","));
        u.setPath(invocation.getClassName() + "." + invocation.getMethodName() + "(" + _params + ")");
        ((RpcInvocation) invocation).setUrl(u);

        byte[] payload = new Gson().toJson(invocation).getBytes();

        ByteArrayEntity entriy = new ByteArrayEntity(payload, ContentType.DEFAULT_BINARY);
        post.setEntity(entriy);
        HttpResponse res = client.execute(post);
        HttpEntity resEntity = res.getEntity();
        byte[] data = EntityUtils.toByteArray(resEntity);
        Message message = gson.fromJson(new String(data), Message.class);
        return new String(message.payload);
    } catch (Exception ex) {
        logger.info("execute error:{}", ex.getMessage());
        throw new RpcException(ex);
    }
}
 
Example 11
Source File: RestJodConverterStressTest.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static void addPartMethod01(File documentFile) throws Exception {

	//String textFileName = "C:/tmp/AnalisiTraffico.xlsx";
	//File file = new File(textFileName);
	File file = documentFile;
	
	//HttpPost post = new HttpPost("http://localhost:8080/jodapp/");
       ///jodapp/converted/document.pdf
       HttpPost httppost = new HttpPost("http://localhost:8080/jodapp/converted/document.pdf");
	
	
	FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
	StringBody stringBody1 = new StringBody("pdf", ContentType.DEFAULT_TEXT);
	
	// 
	MultipartEntityBuilder builder = MultipartEntityBuilder.create();
	builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
	builder.addPart("inputDocument", fileBody);
	builder.addPart("outputFormat", stringBody1);
	HttpEntity entity = builder.build();
	
	//
	httppost.setEntity(entity);
	
	CloseableHttpClient httpclient = HttpClients.createDefault();
	
	CloseableHttpResponse response = httpclient.execute(httppost);
	try {
        int responseStatus = response.getStatusLine().getStatusCode();
        System.out.println("responseStatus: " + responseStatus);
        
		HttpEntity rent = response.getEntity();
		if (rent != null) {
			/*String respoBody = EntityUtils.toString(rent, "UTF-8");
			System.out.println(respoBody); */
			System.out.println("ctype: " + rent.getContentType());
	        System.out.println("length: " + rent.getContentLength());
	        
	        if (responseStatus == 200) {
				// do something useful with the response body
				// and ensure it is fully consumed
				EntityUtils.consume(rent);	
	        } else {
	        	String respoBody = EntityUtils.toString(rent, "UTF-8");
	        	System.err.println("responseStatus: " + responseStatus);
	        	System.err.println(file.getName());
				System.err.println(respoBody);
	        }
		}
	} finally {
		response.close();
	}		

	httpclient.close();
}
 
Example 12
Source File: RestJodConverter.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static void addPartMethod01() throws Exception {

	String textFileName = "C:/tmp/AnalisiTraffico.xlsx";
	File file = new File(textFileName);
	
	//HttpPost post = new HttpPost("http://localhost:8080/jodapp/");
       ///jodapp/converted/document.pdf
       HttpPost post = new HttpPost("http://localhost:8080/jodapp/converted/document.pdf");
	
	
	FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
	StringBody stringBody1 = new StringBody("pdf", ContentType.DEFAULT_TEXT);
	
	// 
	MultipartEntityBuilder builder = MultipartEntityBuilder.create();
	builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
	builder.addPart("inputDocument", fileBody);
	builder.addPart("outputFormat", stringBody1);
	HttpEntity entity = builder.build();
	
	//
	post.setEntity(entity);
	
	CloseableHttpClient client = HttpClients.createDefault();
	
	CloseableHttpResponse response1 = client.execute(post);
	//Object[] response = null;
	
	try {
        HttpEntity entity1 = response1.getEntity();
        //String responseBody = responseAsString(response1);
        int responseStatus = response1.getStatusLine().getStatusCode();
        System.out.println("responseStatus: " + responseStatus);
        
        
        //response = new Object [] {responseStatus, responseBody};

        // do something useful with the response body
        // and ensure it is fully consumed
        //EntityUtils.consume(entity1);
        
        //int length = (int) entity1.getContentLength();
        System.out.println("length: " + entity1.getContentLength());
        System.out.println("ctype: " + entity1.getContentType());
        
        /*
		if (entity1 != null) {
			String respoBody = EntityUtils.toString(entity1, "UTF-8");
			System.out.println(respoBody);
		} */           
        
	} finally {
        response1.close();
	}		

    client.close();
}
 
Example 13
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void uploadDocument02(CloseableHttpClient httpclient) throws IOException {

		System.out.println("uploadDocument(CloseableHttpClient)");
		
        HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/document/upload");

		//File file = new File("C:/tmp/InvoiceProcessing01-workflow.png");        
        File file = new File("c:/users/shatz/Downloads/SimpleTestProject.zip");
        //File file = new File("C:/tmp/testContent.txt");        
                
		System.out.println(file.getName());	
		
		long folderID = 124358812L;
        
		StringBody fnamePart = new StringBody(file.getName(), ContentType.TEXT_PLAIN);
		StringBody folderPart = new StringBody(Long.toString(folderID), ContentType.TEXT_PLAIN);
        FileBody binPart = new FileBody(file, ContentType.DEFAULT_BINARY);        

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("filename", fnamePart)
                .addPart("filedata", binPart)
                .addPart("folderId", folderPart)
                .build();
		
		httppost.setEntity(reqEntity);

		/*
		int timeout = 5; // seconds
		HttpParams httpParams = httpclient.getParams();
		HttpConnectionParams.setConnectionTimeout(
		  httpParams, timeout * 1000); // http.connection.timeout
		HttpConnectionParams.setSoTimeout(
		  httpParams, timeout * 1000); // http.socket.timeout
		*/
		
		CloseableHttpResponse response = httpclient.execute(httppost);
		
		int code = response.getStatusLine().getStatusCode();
		System.out.println("HTTPstatus code: "+ code);
		
		try {
			HttpEntity rent = response.getEntity();
			if (rent != null) {
				String respoBody = EntityUtils.toString(rent, "UTF-8");
				System.out.println(respoBody);
			}
		} finally {
			response.close();
		}
	}
 
Example 14
Source File: ClientConnection.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 4 votes vote down vote up
public ContentType getContentType() {
    return this.contentType == null ? ContentType.DEFAULT_BINARY : this.contentType;
}
 
Example 15
Source File: FileUploadDownloadClient.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
private static ContentBody getContentBody(String fileName, File file) {
  return new FileBody(file, ContentType.DEFAULT_BINARY, fileName);
}
 
Example 16
Source File: FileUploadDownloadClient.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
private static ContentBody getContentBody(String fileName, InputStream inputStream) {
  return new InputStreamBody(inputStream, ContentType.DEFAULT_BINARY, fileName);
}