Example usage for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM

List of usage examples for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM

Introduction

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

Prototype

ContentType APPLICATION_OCTET_STREAM

To view the source code for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM.

Click Source Link

Usage

From source file:com.jkoolcloud.tnt4j.streams.inputs.HttpStreamTest.java

@Test
public void httpFilePostTest() throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    HttpClient client = builder.build();

    URI url = makeURI();/*  w w  w . j  a  va 2  s. c o m*/
    HttpPost post = new HttpPost(url);

    File file = new File(samplesDir, "/http-file/log.txt");
    EntityBuilder entityBuilder = EntityBuilder.create();
    entityBuilder.setFile(file);
    entityBuilder.setContentType(ContentType.TEXT_PLAIN);

    MultipartEntityBuilder builder2 = MultipartEntityBuilder.create();
    builder2.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, "file.ext"); // NON-NLS
    HttpEntity multipart = builder2.build();

    post.setEntity(multipart);

    final HttpResponse returned = client.execute(post);
    assertNotNull(returned);

}

From source file:com.qwazr.utils.json.client.JsonClientAbstract.java

private Request setBodyString(Request request, Object bodyObject) throws JsonProcessingException {
    if (bodyObject == null)
        return request;
    if (bodyObject instanceof String)
        return request.bodyString(bodyObject.toString(), ContentType.TEXT_PLAIN);
    else if (bodyObject instanceof InputStream)
        return request.bodyStream((InputStream) bodyObject, ContentType.APPLICATION_OCTET_STREAM);
    else//w w w .  ja  v  a2s  .  co m
        return request.bodyString(JsonMapper.MAPPER.writeValueAsString(bodyObject),
                ContentType.APPLICATION_JSON);
}

From source file:com.oracle.jes.samples.hellostorage.HttpElementPost.java

public void putData2() throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent())
            .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("192.168.1.5", 8080);
    coreContext.setTargetHost(host);//from  www . j  ava  2s  .c o  m

    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

    try {

        HttpEntity[] requestBodies = {
                new StringEntity("This is the first test request",
                        ContentType.create("text/plain", Consts.UTF_8)),
                new ByteArrayEntity("This is the second test request".getBytes("UTF-8"),
                        ContentType.APPLICATION_OCTET_STREAM),
                new InputStreamEntity(
                        new ByteArrayInputStream(
                                "This is the third test request (will be chunked)".getBytes("UTF-8")),
                        ContentType.APPLICATION_OCTET_STREAM) };

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket);
            }

            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
                    "/servlets-examples/servlet/RequestInfoExample");

            request.setEntity(requestBodies[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:com.joyent.manta.client.multipart.AbstractMultipartManager.java

@Override
public PART uploadPart(final UPLOAD upload, final int partNumber, final String contents) throws IOException {
    validatePartNumber(partNumber);/*from  www.  ja  v a 2s.c o  m*/
    Validate.notNull(contents, "String must not be null");

    HttpEntity entity = new ExposedStringEntity(contents, ContentType.APPLICATION_OCTET_STREAM);

    return uploadPart(upload, partNumber, entity, null);
}

From source file:com.joyent.manta.client.MantaDirectoryListingIteratorTest.java

public void throwsAppropriateExceptionWhenListingObject() throws Exception {
    final String dirPath = "/user/stor/directory";
    final Header contentTypeHeader = new BasicHeader(CONTENT_TYPE,
            ContentType.APPLICATION_OCTET_STREAM.toString());

    when(responseEntity.getContentType()).thenReturn(contentTypeHeader);
    when(response.getFirstHeader(CONTENT_TYPE)).thenReturn(contentTypeHeader);
    when(response.getAllHeaders()).thenReturn(new Header[] { contentTypeHeader });

    // uncomment once it's okay to call next before hasNext
    Assert.expectThrows(MantaUnexpectedObjectTypeException.class,
            () -> new MantaDirectoryListingIterator(dirPath, httpHelper, MAX_RESULTS).next());

    Assert.expectThrows(MantaUnexpectedObjectTypeException.class,
            () -> new MantaDirectoryListingIterator(dirPath, httpHelper, MAX_RESULTS).hasNext());
}

From source file:net.ychron.unirestinst.request.body.MultipartBody.java

public MultipartBody field(String name, Object value, boolean file, String contentType) {
    List<Object> list = parameters.get(name);
    if (list == null)
        list = new LinkedList<Object>();
    list.add(value);//ww  w . j  a  va 2s. c o  m
    parameters.put(name, list);

    ContentType type = null;
    if (contentType != null && contentType.length() > 0) {
        type = ContentType.parse(contentType);
    } else if (file) {
        type = ContentType.APPLICATION_OCTET_STREAM;
    } else {
        type = ContentType.APPLICATION_FORM_URLENCODED.withCharset(UTF_8);
    }
    contentTypes.put(name, type);

    if (!hasFile && file) {
        hasFile = true;
    }

    return this;
}

From source file:net.ladenthin.snowman.imager.run.uploader.Uploader.java

@Override
public void run() {
    final CImager cs = ConfigurationSingleton.ConfigurationSingleton.getImager();
    final String url = cs.getSnowmanServer().getApiUrl();
    for (;;) {//  w w w . ja va 2s  . com
        File obtainedFile;
        for (;;) {
            if (WatchdogSingleton.WatchdogSingleton.getWatchdog().getKillFlag() == true) {
                LOGGER.trace("killFlag == true");
                return;
            }
            obtainedFile = FileAssignationSingleton.FileAssignationSingleton.obtainFile();

            if (obtainedFile == null) {
                Imager.waitALittleBit(300);
                continue;
            } else {
                break;
            }
        }

        boolean doUpload = true;
        while (doUpload) {
            try {
                try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
                    final HttpPost httppost = new HttpPost(url);
                    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                    final FileBody fb = new FileBody(obtainedFile, ContentType.APPLICATION_OCTET_STREAM);

                    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                    builder.addPart(uploadNameCameraimage, fb);
                    builder.addTextBody(uploadNameFilename, obtainedFile.getName());
                    builder.addTextBody(uploadNameUsername, cs.getSnowmanServer().getUsername());
                    builder.addTextBody(uploadNamePassword, cs.getSnowmanServer().getPassword());
                    builder.addTextBody(uploadNameCameraname, cs.getSnowmanServer().getCameraname());

                    final HttpEntity httpEntity = builder.build();
                    httppost.setEntity(httpEntity);

                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("executing request " + httppost.getRequestLine());
                    }

                    try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                        if (LOGGER.isTraceEnabled()) {
                            LOGGER.trace("response.getStatusLine(): " + response.getStatusLine());
                        }
                        final HttpEntity resEntity = response.getEntity();
                        if (resEntity != null) {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("RresEntity.getContentLength(): " + resEntity.getContentLength());
                            }
                        }
                        final String resString = EntityUtils.toString(resEntity).trim();
                        EntityUtils.consume(resEntity);
                        if (resString.equals(responseSuccess)) {
                            doUpload = false;
                            LOGGER.trace("true: resString.equals(responseSuccess)");
                            LOGGER.trace("resString: {}", resString);
                        } else {
                            LOGGER.warn("false: resString.equals(responseSuccess)");
                            LOGGER.warn("resString: {}", resString);
                            // do not flood log files if an error occurred
                            Imager.waitALittleBit(2000);
                        }
                    }
                }
            } catch (NoHttpResponseException | SocketException e) {
                logIOExceptionAndWait(e);
            } catch (IOException e) {
                LOGGER.warn("Found unknown IOException", e);
            }
        }

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("delete obtainedFile {}", obtainedFile);
        }
        final boolean delete = obtainedFile.delete();
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("delete success {}", delete);
        }
        FileAssignationSingleton.FileAssignationSingleton.freeFile(obtainedFile);
    }
}

From source file:com.epam.reportportal.service.ReportPortalErrorHandlerTest.java

@Test
public void hasError() throws Exception {
    //  given:/*from   ww  w .  ja v a2 s.  co m*/
    LinkedListMultimap<String, String> validHeaders = LinkedListMultimap.create();
    validHeaders.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());

    LinkedListMultimap<String, String> validHeaders2 = LinkedListMultimap.create();
    validHeaders2.put(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");

    LinkedListMultimap<String, String> invalidHeaders1 = LinkedListMultimap.create();
    invalidHeaders1.put(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_HTML.getMimeType());

    LinkedListMultimap<String, String> invalidHeaders2 = LinkedListMultimap.create();
    invalidHeaders2.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM.getMimeType());

    //  then:
    assertTrue(reportPortalErrorHandler.hasError(createFakeResponse(500, validHeaders)));
    assertTrue(reportPortalErrorHandler.hasError(createFakeResponse(404, validHeaders)));

    assertTrue(reportPortalErrorHandler.hasError(createFakeResponse(200, invalidHeaders1)));
    assertTrue(reportPortalErrorHandler.hasError(createFakeResponse(200, invalidHeaders2)));

    //      and:
    assertFalse(reportPortalErrorHandler.hasError(createFakeResponse(200, validHeaders)));
    assertFalse(reportPortalErrorHandler.hasError(createFakeResponse(200, validHeaders2)));
}

From source file:com.joyent.manta.client.multipart.AbstractMultipartManager.java

@Override
public PART uploadPart(final UPLOAD upload, final int partNumber, final byte[] bytes) throws IOException {
    validatePartNumber(partNumber);//from   ww  w .j  a  v a2s  . com
    Validate.notNull(bytes, "Byte array must not be null");

    HttpEntity entity = new ExposedByteArrayEntity(bytes, ContentType.APPLICATION_OCTET_STREAM);
    return uploadPart(upload, partNumber, entity, null);
}