Java 类org.apache.http.entity.mime.content.InputStreamBody 实例源码

项目:purecloud-iot    文件:TestMultipartContentBody.java   
@Test
public void testInputStreamBody() throws Exception {
    final byte[] stuff = "Stuff".getBytes(Consts.ASCII);
    final InputStreamBody b1 = new InputStreamBody(new ByteArrayInputStream(stuff), "stuff");
    Assert.assertEquals(-1, b1.getContentLength());

    Assert.assertNull(b1.getCharset());
    Assert.assertEquals("stuff", b1.getFilename());
    Assert.assertEquals("application/octet-stream", b1.getMimeType());
    Assert.assertEquals("application", b1.getMediaType());
    Assert.assertEquals("octet-stream", b1.getSubType());

    Assert.assertEquals(MIME.ENC_BINARY, b1.getTransferEncoding());

    final InputStreamBody b2 = new InputStreamBody(
            new ByteArrayInputStream(stuff), ContentType.create("some/stuff"), "stuff");
    Assert.assertEquals(-1, b2.getContentLength());
    Assert.assertNull(b2.getCharset());
    Assert.assertEquals("stuff", b2.getFilename());
    Assert.assertEquals("some/stuff", b2.getMimeType());
    Assert.assertEquals("some", b2.getMediaType());
    Assert.assertEquals("stuff", b2.getSubType());

    Assert.assertEquals(MIME.ENC_BINARY, b2.getTransferEncoding());
}
项目:Weixin    文件:MaterialAPI.java   
/**
 * 新增其他类型永久素材
 * @param access_token
 * @param mediaType
 * @param inputStream   多媒体文件有格式和大小限制,如下:
                    图片(image): 128K,支持JPG格式
                    语音(voice):256K,播放长度不超过60s,支持AMR\MP3格式
                    视频(video):1MB,支持MP4格式
                    缩略图(thumb):64KB,支持JPG格式
 * @param description 视频文件类型额外字段,其它类型不用添加
 * @return
 */
public static Media materialAdd_material(String access_token,MediaType mediaType,InputStream inputStream,Description description){
    HttpPost httpPost = new HttpPost(MEDIA_URI+"/cgi-bin/material/add_material");
       @SuppressWarnings("deprecation")
    InputStreamBody inputStreamBody = new InputStreamBody(inputStream, mediaType.mimeType(),"temp."+mediaType.fileSuffix());
       MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
            .addPart("media", inputStreamBody);
    if(description != null){
        multipartEntityBuilder.addTextBody("description", JsonUtil.toJSONString(description));
    }
    HttpEntity reqEntity = multipartEntityBuilder.addTextBody("access_token", access_token)
                     .addTextBody("type",mediaType.uploadType())
                     .build();
       httpPost.setEntity(reqEntity);
    return LocalHttpClient.executeJsonResult(httpPost,Media.class);
}
项目:blynk-server    文件:OTATest.java   
@Test
public void testOTAWrongToken() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(400, response.getStatusLine().getStatusCode());
        String error = consumeText(response);

        assertNotNull(error);
        assertEquals("Invalid token.", error);
    }
}
项目:blynk-server    文件:OTATest.java   
@Test
public void testAuthorizationFailed() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString("123:123".getBytes()));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(403, response.getStatusLine().getStatusCode());
        String error = consumeText(response);

        assertNotNull(error);
        assertEquals("Authentication failed.", error);
    }
}
项目:SEAL    文件:ClueWebSearcher.java   
/** Utility method:
 * Formulate an HTTP POST request to upload the batch query file
 * @param queryBody
 * @return
 * @throws UnsupportedEncodingException
 */
private HttpPost makePost(String queryBody) throws UnsupportedEncodingException {
    HttpPost post = new HttpPost(ClueWebSearcher.BATCH_CATB_BASEURL);
    InputStreamBody qparams = 
        new InputStreamBody(
                new ReaderInputStream(new StringReader(queryBody)),
                "text/plain",
        "query.txt");

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("viewstatus", new StringBody("1")); 
    entity.addPart("indextype",  new StringBody("catbparams"));
    entity.addPart("countmax",   new StringBody("100"));
    entity.addPart("formattype", new StringBody(format));
    entity.addPart("infile",     qparams);

    post.setEntity(entity);
    return post;
}
项目:jira-client    文件:RestClient.java   
private JSON request(HttpEntityEnclosingRequestBase req, Issue.NewAttachment... attachments)
    throws RestException, IOException {
    if (attachments != null) {
        req.setHeader("X-Atlassian-Token", "nocheck");
        MultipartEntity ent = new MultipartEntity();
        for(Issue.NewAttachment attachment : attachments) {
            String filename = attachment.getFilename();
            Object content = attachment.getContent();
            if (content instanceof byte[]) {
                ent.addPart("file", new ByteArrayBody((byte[]) content, filename));
            } else if (content instanceof InputStream) {
                ent.addPart("file", new InputStreamBody((InputStream) content, filename));
            } else if (content instanceof File) {
                ent.addPart("file", new FileBody((File) content, filename));
            } else if (content == null) {
                throw new IllegalArgumentException("Missing content for the file " + filename);
            } else {
                throw new IllegalArgumentException(
                    "Expected file type byte[], java.io.InputStream or java.io.File but provided " +
                        content.getClass().getName() + " for the file " + filename);
            }
        }
        req.setEntity(ent);
    }
    return request(req);
}
项目:puppetdb-javaclient    文件:HttpComponentsConnector.java   
@Override
public <V> V postUpload(String uri, Map<String, String> stringParts, InputStream in, String mimeType, String fileName,
        final long fileSize, Class<V> type) throws IOException {
    HttpPost request = new HttpPost(createURI(uri));
    configureRequest(request);

    MultipartEntity entity = new MultipartEntity();
    for(Map.Entry<String, String> entry : stringParts.entrySet())
        entity.addPart(entry.getKey(), StringBody.create(entry.getValue(), "text/plain", UTF_8));

    entity.addPart("file", new InputStreamBody(in, mimeType, fileName) {
        @Override
        public long getContentLength() {
            return fileSize;
        }
    });
    request.setEntity(entity);
    return executeRequest(request, type, null);
}
项目:p1-android    文件:BatchUtil.java   
public static void addBitmap(MultipartEntity multipartEntity, Bitmap image,
        String imageId) {
    int measureId = PerformanceMeasure.startMeasure();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    image.compress(CompressFormat.JPEG, BitmapUtils.JPEG_COMPRESSION_LEVEL,
            bos);
    ByteArrayInputStream bs = new ByteArrayInputStream(bos.toByteArray());

    InputStreamBody body = new InputStreamBody(bs, "image/jpeg", imageId);
    multipartEntity.addPart(imageId, body);
    PerformanceMeasure.endMeasure(measureId, "Jpeg compression time");

    Log.d(TAG,
            "Multipart entry after bitmap addition: "
                    + multipartEntity.toString());
}
项目:java-http-fluent    文件:Http.java   
@Override
protected HttpUriRequest createRequest() throws IOException {
    MultipartEntity entity = new MultipartEntity();          
    List<NameValuePair> dataList = getData();
    for (NameValuePair d : dataList) {
        entity.addPart(new FormBodyPart(d.getName(), new StringBody(d.getValue(), Charset.forName("utf-8"))));
    }
    for (Map.Entry<String, InputStreamBody> entry : files.entrySet()) {
        entity.addPart(new FormBodyPart(entry.getKey(), entry.getValue()));
    }


    final HttpPost request = new HttpPost(url);

    if(this.sendProgressListener != null) {
        CountingRequestEntity countingEntity = new CountingRequestEntity(entity, this.sendProgressListener);
        request.setEntity(countingEntity);
    } else {
        request.setEntity(entity);
    }
    return request;
}
项目:box-java-sdk-v2    文件:BoxFileUploadRequestObject.java   
private static MultipartEntityWithProgressListener getNewFileMultipartEntity(final String parentId, final InputStream inputStream, final String fileName)
    throws BoxRestException, UnsupportedEncodingException {
    MultipartEntityWithProgressListener me = new MultipartEntityWithProgressListener(HttpMultipartMode.BROWSER_COMPATIBLE);
    me.addPart(Constants.FOLDER_ID, new StringBody(parentId));
    String date = ISO8601DateParser.toString(new Date());
    if (me.getPart(KEY_CONTENT_CREATED_AT) == null) {
        me.addPart(KEY_CONTENT_CREATED_AT, new StringBody(date));
    }
    if (me.getPart(KEY_CONTENT_MODIFIED_AT) == null) {
        me.addPart(KEY_CONTENT_MODIFIED_AT, new StringBody(date));
    }

    me.addPart(fileName, new InputStreamBody(inputStream, fileName));

    return me;
}
项目:infoarchive-sip-sdk    文件:ApacheHttpClient.java   
private ContentBody newContentBody(Part part) {
  ContentType contentType = ContentType.create(part.getMediaType());
  if (part instanceof TextPart) {
    TextPart textPart = (TextPart)part;
    return new StringBody(textPart.getText(), contentType);
  }
  BinaryPart binaryPart = (BinaryPart)part;
  return new InputStreamBody(binaryPart.getData(), contentType, binaryPart.getDownloadName());
}
项目:purecloud-iot    文件:TestMultipartFormHttpEntity.java   
@Test
public void testNonRepeatable() throws Exception {
    final HttpEntity entity = MultipartEntityBuilder.create()
        .addPart("p1", new InputStreamBody(
            new ByteArrayInputStream("blah blah".getBytes()), ContentType.DEFAULT_BINARY))
        .addPart("p2", new InputStreamBody(
            new ByteArrayInputStream("yada yada".getBytes()), ContentType.DEFAULT_BINARY))
        .build();
    Assert.assertFalse(entity.isRepeatable());
    Assert.assertTrue(entity.isChunked());
    Assert.assertTrue(entity.isStreaming());

    Assert.assertTrue(entity.getContentLength() == -1);
}
项目:semiot-platform    文件:OSGiApiService.java   
public Observable<String> sendPostUploadFile(InputStream inputStream,
                                             String filename, String pid,
                                             Map<String, String> parameters) {
  return Observable.create(o -> {
    try {
      postConfigureStart(pid, parameters);

      // загрузка файла
      InputStreamBody bin = new InputStreamBody(inputStream,
          filename);

      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart("bundlefile", bin);
      reqEntity.addPart("action", new StringBody("install"));
      reqEntity.addPart("bundlestart", new StringBody("start"));
      reqEntity.addPart("bundlestartlevel", new StringBody("1"));
      postHttpClientQuery(URL_BUNDLES, reqEntity, Collections
          .list(new BasicHeader("Accept", "application/json")));

      o.onNext("");
    } catch (Exception e) {
      throw Exceptions.propagate(e);
    }
    o.onCompleted();
  }).subscribeOn(Schedulers.from(mes)).cast(String.class);

}
项目:Weixin    文件:MediaAPI.java   
/**
 * 上传媒体文件
 * 媒体文件在后台保存时间为3天,即3天后media_id失效。
 * @param access_token
 * @param mediaType
 * @param inputStream   多媒体文件有格式和大小限制,如下:
                    图片(image): 128K,支持JPG格式
                    语音(voice):256K,播放长度不超过60s,支持AMR\MP3格式
                    视频(video):1MB,支持MP4格式
                    缩略图(thumb):64KB,支持JPG格式
 * @return
 */
public static Media mediaUpload(String access_token,MediaType mediaType,InputStream inputStream){
    HttpPost httpPost = new HttpPost(MEDIA_URI+"/cgi-bin/media/upload");
       @SuppressWarnings("deprecation")
    InputStreamBody inputStreamBody = new InputStreamBody(inputStream, mediaType.mimeType(),"temp."+mediaType.fileSuffix());
    HttpEntity reqEntity = MultipartEntityBuilder.create()
             .addPart("media",inputStreamBody)
                .addTextBody("access_token", access_token)
                .addTextBody("type",mediaType.uploadType())
                .build();
       httpPost.setEntity(reqEntity);
    return LocalHttpClient.executeJsonResult(httpPost,Media.class);
}
项目:JavaTelegramBot-API    文件:Utils.java   
/**
 * Adds an input file to a request, with the given field name.
 *
 * @param request The request to be added to.
 * @param fieldName The name of the field.
 * @param inputFile The input file.
 */
public static void processInputFileField(MultipartBody request, String fieldName, InputFile inputFile) {
    String fileId = inputFile.getFileID();
    if (fileId != null) {
        request.field(fieldName, fileId, false);
    } else if (inputFile.getInputStream() != null) {
        request.field(fieldName, new InputStreamBody(inputFile.getInputStream(), inputFile.getFileName()), true);
    } else { // assume file is not null (this is existing behaviour as of 1.5.1)
        request.field(fieldName, new FileContainer(inputFile), true);
    }
}
项目:blynk-server    文件:UploadAPITest.java   
private String upload(String filename) throws Exception {
    InputStream logoStream = UploadAPITest.class.getResourceAsStream("/" + filename);

    HttpPost post = new HttpPost("http://localhost:" + httpPort + "/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 = consumeText(response);

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

    return staticPath;
}
项目:blynk-server    文件:OTATest.java   
@Test
public void testImprovedUploadMethod() throws Exception {
    clientPair.appClient.send("getToken 1");
    String token = clientPair.appClient.getBody();

    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + token);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

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

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

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(new BlynkInternalMessage(7777, b("ota " + responseUrl))));

    HttpGet index = new HttpGet("http://localhost:" + httpPort + path);

    try (CloseableHttpResponse response = httpclient.execute(index)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("application/octet-stream", response.getHeaders("Content-Type")[0].getValue());
    }
}
项目:blynk-server    文件:OTATest.java   
@Test
public void testOTAFailedWhenNoDevice() throws Exception {
    clientPair.appClient.send("getToken 1");
    String token = clientPair.appClient.getBody();

    clientPair.hardwareClient.stop();

    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + token);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(400, response.getStatusLine().getStatusCode());
        String error = consumeText(response);

        assertNotNull(error);
        assertEquals("No device in session.", error);
    }
}
项目:blynk-server    文件:OTATest.java   
@Test
public void basicOTAForAllDevices() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

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

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

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(new BlynkInternalMessage(7777, b("ota " + responseUrl))));

    HttpGet index = new HttpGet("http://localhost:" + httpPort + path);

    try (CloseableHttpResponse response = httpclient.execute(index)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("application/octet-stream", response.getHeaders("Content-Type")[0].getValue());
    }
}
项目:blynk-server    文件:OTATest.java   
@Test
public void testStopOTA() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

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

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }
    String responseUrl = "http://127.0.0.1:18080" + path;

    HttpGet stopOta = new HttpGet(httpsAdminServerUrl + "/ota/stop");
    stopOta.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    try (CloseableHttpResponse response = httpclient.execute(stopOta)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }

    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));
    verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(ok(1)));
    verify(clientPair.hardwareClient.responseMock, never()).channelRead(any(), eq(new BlynkInternalMessage(7777, b("ota " + responseUrl))));
}
项目:p3-batchrefine    文件:RefineHTTPClient.java   
private String createProjectAndUpload(URL original) throws IOException {
    CloseableHttpResponse response = null;

    URLConnection connection = original.openConnection();

    try (InputStream iStream = connection.getInputStream()) {

        /*
         * Refine requires projects to be named, but these are not important
* for us, so we just use a random string.
*/
        String name = RandomStringUtils
                .randomAlphanumeric(IDENTIFIER_LENGTH);

        HttpEntity entity = MultipartEntityBuilder
                .create()
                .addPart("project-file",
                        new InputStreamBody(iStream, contentType(original, connection), BOGUS_FILENAME))
                .addPart("project-name",
                        new StringBody(name, ContentType.TEXT_PLAIN))
                .build();

        response = doPost("/command/core/create-project-from-upload",
                entity);

        URI projectURI = new URI(response.getFirstHeader("Location")
                .getValue());

        //TODO check if this is always UTF-8
        return URLEncodedUtils.parse(projectURI, "UTF-8").get(0).getValue();

    } catch (Exception e) {
        throw launderedException(e);
    } finally {
        Utils.safeClose(response);
    }
}
项目:visearch-sdk-java    文件:ViSearchHttpClientImpl.java   
private static HttpUriRequest buildPostRequestForImage(String url, Multimap<String, String> params, InputStream inputStream, String filename) {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    ContentType contentType = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), UTF8_CHARSET);
    for (Map.Entry<String, String> entry : params.entries()) {
        builder.addTextBody(entry.getKey(), entry.getValue(), contentType);
    }
    builder.addPart(ViSearchHttpConstants.IMAGE, new InputStreamBody(inputStream, filename));
    HttpEntity entity = builder.build();
    return buildMultipartPostRequest(url, entity);
}
项目:restz-framework    文件:HC400Executor.java   
private HttpEntity buildMultipart(MultipartEntityBuilder entity)
throws UnsupportedEncodingException
{
    final MultipartEntity multipartEntity = new MultipartEntity();

    final List<Part> parts = entity.getParts();
    for(Part part : parts)
        if(part instanceof TextPart)
        {
            final TextPart textPart = (TextPart) part;
            multipartEntity.addPart(part.getName(), new StringBody(textPart.getText(), textPart.getContentType(), Charset.defaultCharset()));
        }
        else
        if(part instanceof InputStreamPart)
        {
            final InputStreamPart inPart = (InputStreamPart) part;
            multipartEntity.addPart(inPart.getName(), new InputStreamBody(inPart.getContent(), inPart.getContentType(), inPart.getFileName()));
        }
        else
        if(part instanceof FilePart)
        {
            final FilePart filePart = (FilePart) part;
            multipartEntity.addPart(filePart.getName(), new FileBody(filePart.getContent(), filePart.getContentType()));
        }
        else
        if(part instanceof ByteArrayPart)
        {
            final ByteArrayPart byteArrayPart = (ByteArrayPart) part;
            final byte[] byteArray = byteArrayPart.getContent();

            final ByteArrayInputStream byteArrayAsInputStream = new ByteArrayInputStream(byteArray);
            multipartEntity.addPart(byteArrayPart.getName(), new InputStreamBody(byteArrayAsInputStream, byteArrayPart.getContentType(), byteArrayPart.getFileName()));
        }

    final HttpEntity httpEntity = multipartEntity;
    return httpEntity;
}
项目:android-lite-http    文件:PostReceiver.java   
private HttpEntity getMultipartEntity(String path) throws UnsupportedEncodingException, FileNotFoundException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("stringKey", new StringBody("StringBody", "text/plain", Charset.forName("utf-8")));
    byte[] bytes = new byte[]{1, 2, 3};
    entity.addPart("bytesKey", new ByteArrayBody(bytes, "bytesfilename"));
    entity.addPart("fileKey", new FileBody(new File(path + "well.png")));
    entity.addPart("isKey", new InputStreamBody(new FileInputStream(new File(path + "well.png")), "iswell.png"));

    return entity;
}
项目:helpstack-android    文件:HSUploadAttachment.java   
public InputStreamBody generateStreamToUpload() throws FileNotFoundException {
       InputStream stream = generateInputStreamToUpload();

       String attachmentFileName = "attachment";
       if (attachment.getFileName()!=null) {
           attachmentFileName = attachment.getFileName();
       }

    InputStreamBody body =  new InputStreamBody(stream, attachment.getMimeType(), attachmentFileName);
    return body;
}
项目:testgrid    文件:HttpFileTransferSource.java   
@Override
public void push(String token, Collection<File> fileList) throws Exception {
    File file = validate(fileList);
    if (file != null)
        throw new Exception("Validate File[ " + file.getAbsolutePath() + "] failed.");
    CloseableHttpResponse response = null;
    InputStream in = null;
    List<InputStream> ins = new ArrayList<InputStream>();
    try {
        client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().addTextBody("token", token);
        for (File f : fileList) {
            if (!f.exists())
                throw new FileNotFoundException("File:" + f.getAbsolutePath() + " didn't exits. Stop upload.");
            in = new FileInputStream(f);
            ins.add(in);
            builder.addPart(f.getName(), new InputStreamBody(in, f.getName()));
            // builder.addBinaryBody( f.getName(), in );
        }
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK)
            throw new Exception("Pushing files failed. Post return code:" + statusCode);
    } finally {
        CommonUtils.closeQuietly(response);
        for (InputStream i : ins) {
            CommonUtils.closeQuietly(i);
        }
        CommonUtils.closeQuietly(client);
    }

}
项目:testgrid    文件:HttpPutFTChannel.java   
@Override
public boolean apply(LogConnector log) {
    boolean result = false;
    CloseableHttpResponse response = null;
    InputStream in = null;
    CloseableHttpClient client = null;
    File f = new File("testupload" + CommonUtils.generateToken(3) + ".tmp");
    try {
        if (!f.exists())
            f.createNewFile();
        client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(getProperty("postUrl", ""));
        String token = "testupload";
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().addTextBody("token", token);
        in = new FileInputStream(f);
        builder.addPart(f.getName(), new InputStreamBody(in, f.getName()));
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK)
            result = true;
        else {
            if (log != null)
                log.error("Apply Pushing files to " + getProperty("postUrl", "") + " failed. Post return code:" + statusCode);
            else
                System.err.println("Apply Pushing files to " + getProperty("postUrl", "") + " failed. Post return code:" + statusCode);
        }
    } catch (Exception ex) {
        if (log != null)
            log.error("Apply HttpPutChannel failed.", ex);
    } finally {
        CommonUtils.closeQuietly(response);
        CommonUtils.closeQuietly(in);
        CommonUtils.closeQuietly(client);
        if (f != null)
            f.delete();
    }
    return result;
}
项目:clients    文件:AbstractPost.java   
@Override
protected HttpEntity buildEntity() {
    return MultipartEntityBuilder
            .create()
            .addPart("post[file]",
                    new InputStreamBody(getData(), getFilename()))
            .addPart("post[tags]",
                    new StringBody(getTags(), ContentType.TEXT_PLAIN))
            .addPart(
                    "post[description]",
                    new StringBody(getDescription(),
                            ContentType.TEXT_PLAIN)).build();
}
项目:p1-android    文件:BatchUtil.java   
public static void addJpeg(MultipartEntity multipartEntity,
        byte[] compressedJpeg, String imageId) {
    ByteArrayInputStream bs = new ByteArrayInputStream(compressedJpeg);

    InputStreamBody body = new InputStreamBody(bs, "image/jpeg", imageId);
    multipartEntity.addPart(imageId, body);
}
项目:tisana4j    文件:RestClient.java   
@Override
public <T> T postData( URL url, String filename, InputStream content, Class<T> responseClass,
        Map<String, String> newHeaders ) throws RestException
{

    try
    {
        HttpPost post = new HttpPost( url.toURI() );

        prepareRequest( post, newHeaders );

        InputStreamBody body = new InputStreamBody( content, filename );

        HttpEntity entity = MultipartEntityBuilder.create()
                .addPart( "file", body )
                .build();

        post.setEntity( entity );
        HttpResponse response = execute( post );
        if ( responseClass == null || response.getEntity() == null )
        {
            parseResponseHeaders( response );
            EntityUtils.consumeQuietly( response.getEntity() );
            return null;
        }
        return readObject( responseClass, response );
    }
    catch ( URISyntaxException | ParseException e )
    {
        throw new RuntimeRestException( e );
    }
}
项目:box-java-sdk-v2    文件:BoxFileUploadRequestObject.java   
private static MultipartEntityWithProgressListener getNewVersionMultipartEntity(final String name, final InputStream inputStream)
    throws UnsupportedEncodingException {
    MultipartEntityWithProgressListener me = new MultipartEntityWithProgressListener(HttpMultipartMode.BROWSER_COMPATIBLE);
    me.addPart(name, new InputStreamBody(inputStream, name));

    if (me.getPart(KEY_CONTENT_MODIFIED_AT) == null) {
        me.addPart(KEY_CONTENT_MODIFIED_AT, new StringBody(ISO8601DateParser.toString(new Date())));
    }
    return me;
}
项目:java-restclient    文件:HTTPCPartVisitor.java   
@Override
public void visitInputStreamPart(InputStreamPart part) {
    builder.addPart(part.getName(), new InputStreamBody(part.getContent(), adaptContentType(part.getContentType())));
}
项目:Brutusin-RPC    文件:HttpEndpoint.java   
private CloseableHttpResponse doExec(String serviceId, JsonNode input, HttpMethod httpMethod, final ProgressCallback progressCallback) throws IOException {
    try {
        RpcRequest request = new RpcRequest();
        request.setJsonrpc("2.0");
        request.setMethod(serviceId);
        request.setParams(input);
        final String payload = JsonCodec.getInstance().transform(request);
        final HttpUriRequest req;
        if (httpMethod == HttpMethod.GET) {
            String urlparam = URLEncoder.encode(payload, "UTF-8");
            req = new HttpGet(this.endpoint + "?jsonrpc=" + urlparam);
        } else {
            HttpEntityEnclosingRequestBase reqBase;
            if (httpMethod == HttpMethod.POST) {
                reqBase = new HttpPost(this.endpoint);
            } else if (httpMethod == HttpMethod.PUT) {
                reqBase = new HttpPut(this.endpoint);
            } else {
                throw new AssertionError();
            }
            req = reqBase;
            HttpEntity entity;
            Map<String, InputStream> files = JsonCodec.getInstance().getStreams(input);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.STRICT);
            builder.addPart("jsonrpc", new StringBody(payload, ContentType.APPLICATION_JSON));
            if (files != null && !files.isEmpty()) {
                files = sortFiles(files);
                for (Map.Entry<String, InputStream> entrySet : files.entrySet()) {
                    String key = entrySet.getKey();
                    InputStream is = entrySet.getValue();
                    if (is instanceof MetaDataInputStream) {
                        MetaDataInputStream mis = (MetaDataInputStream) is;
                        builder.addPart(key, new InputStreamBody(mis, mis.getName()));
                    } else {
                        builder.addPart(key, new InputStreamBody(is, key));
                    }
                }
            }
            entity = builder.build();
            if (progressCallback != null) {
                entity = new ProgressHttpEntityWrapper(entity, progressCallback);
            }
            reqBase.setEntity(entity);
        }
        HttpClientContext context = contexts.get();
        if (this.clientContextFactory != null && context == null) {
            context = clientContextFactory.create();
            contexts.set(context);
        }
        CloseableHttpResponse ret = this.httpClient.execute(req, context);
        return ret;
    } catch (ConnectException ex) {
        loaded = false;
        throw ex;
    }
}
项目:purecloud-iot    文件:MultipartEntityBuilder.java   
public MultipartEntityBuilder addBinaryBody(
        final String name, final InputStream stream, final ContentType contentType,
        final String filename) {
    return addPart(name, new InputStreamBody(stream, contentType, filename));
}
项目:purecloud-iot    文件:TestMultipartForm.java   
@Test
public void testMultipartFormBinaryParts() throws Exception {
    tmpfile = File.createTempFile("tmp", ".bin");
    final Writer writer = new FileWriter(tmpfile);
    try {
        writer.append("some random whatever");
    } finally {
        writer.close();
    }

    final FormBodyPart p1 = FormBodyPartBuilder.create(
            "field1",
            new FileBody(tmpfile)).build();
    @SuppressWarnings("resource")
    final FormBodyPart p2 = FormBodyPartBuilder.create(
            "field2",
            new InputStreamBody(new FileInputStream(tmpfile), "file.tmp")).build();
    final HttpStrictMultipart multipart = new HttpStrictMultipart(null, "foo",
            Arrays.asList(p1, p2));

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    multipart.writeTo(out);
    out.close();

    final String expected =
        "--foo\r\n" +
        "Content-Disposition: form-data; name=\"field1\"; " +
            "filename=\"" + tmpfile.getName() + "\"\r\n" +
        "Content-Type: application/octet-stream\r\n" +
        "Content-Transfer-Encoding: binary\r\n" +
        "\r\n" +
        "some random whatever\r\n" +
        "--foo\r\n" +
        "Content-Disposition: form-data; name=\"field2\"; " +
            "filename=\"file.tmp\"\r\n" +
        "Content-Type: application/octet-stream\r\n" +
        "Content-Transfer-Encoding: binary\r\n" +
        "\r\n" +
        "some random whatever\r\n" +
        "--foo--\r\n";
    final String s = out.toString("US-ASCII");
    Assert.assertEquals(expected, s);
    Assert.assertEquals(-1, multipart.getTotalLength());
}
项目:purecloud-iot    文件:TestMultipartForm.java   
@Test
public void testMultipartFormStrict() throws Exception {
    tmpfile = File.createTempFile("tmp", ".bin");
    final Writer writer = new FileWriter(tmpfile);
    try {
        writer.append("some random whatever");
    } finally {
        writer.close();
    }

    final FormBodyPart p1 = FormBodyPartBuilder.create(
            "field1",
            new FileBody(tmpfile)).build();
    final FormBodyPart p2 = FormBodyPartBuilder.create(
            "field2",
            new FileBody(tmpfile, ContentType.create("text/plain", "ANSI_X3.4-1968"), "test-file")).build();
    @SuppressWarnings("resource")
    final FormBodyPart p3 = FormBodyPartBuilder.create(
            "field3",
            new InputStreamBody(new FileInputStream(tmpfile), "file.tmp")).build();
    final HttpStrictMultipart multipart = new HttpStrictMultipart(null, "foo",
            Arrays.asList(p1, p2, p3));

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    multipart.writeTo(out);
    out.close();

    final String expected =
        "--foo\r\n" +
        "Content-Disposition: form-data; name=\"field1\"; " +
            "filename=\"" + tmpfile.getName() + "\"\r\n" +
        "Content-Type: application/octet-stream\r\n" +
        "Content-Transfer-Encoding: binary\r\n" +
        "\r\n" +
        "some random whatever\r\n" +
        "--foo\r\n" +
        "Content-Disposition: form-data; name=\"field2\"; " +
            "filename=\"test-file\"\r\n" +
        "Content-Type: text/plain; charset=US-ASCII\r\n" +
        "Content-Transfer-Encoding: binary\r\n" +
        "\r\n" +
        "some random whatever\r\n" +
        "--foo\r\n" +
        "Content-Disposition: form-data; name=\"field3\"; " +
            "filename=\"file.tmp\"\r\n" +
        "Content-Type: application/octet-stream\r\n" +
        "Content-Transfer-Encoding: binary\r\n" +
        "\r\n" +
        "some random whatever\r\n" +
        "--foo--\r\n";
    final String s = out.toString("US-ASCII");
    Assert.assertEquals(expected, s);
    Assert.assertEquals(-1, multipart.getTotalLength());
}
项目:purecloud-iot    文件:TestMultipartForm.java   
@Test
public void testMultipartFormRFC6532() throws Exception {
    tmpfile = File.createTempFile("tmp", ".bin");
    final Writer writer = new FileWriter(tmpfile);
    try {
        writer.append("some random whatever");
    } finally {
        writer.close();
    }

    final FormBodyPart p1 = FormBodyPartBuilder.create(
            "field1\u0414",
            new FileBody(tmpfile)).build();
    final FormBodyPart p2 = FormBodyPartBuilder.create(
            "field2",
            new FileBody(tmpfile, ContentType.create("text/plain", "ANSI_X3.4-1968"), "test-file")).build();
    @SuppressWarnings("resource")
    final FormBodyPart p3 = FormBodyPartBuilder.create(
            "field3",
            new InputStreamBody(new FileInputStream(tmpfile), "file.tmp")).build();
    final HttpRFC6532Multipart multipart = new HttpRFC6532Multipart(null, "foo",
            Arrays.asList(p1, p2, p3));

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    multipart.writeTo(out);
    out.close();

    final String expected =
        "--foo\r\n" +
        "Content-Disposition: form-data; name=\"field1\u0414\"; " +
            "filename=\"" + tmpfile.getName() + "\"\r\n" +
        "Content-Type: application/octet-stream\r\n" +
        "Content-Transfer-Encoding: binary\r\n" +
        "\r\n" +
        "some random whatever\r\n" +
        "--foo\r\n" +
        "Content-Disposition: form-data; name=\"field2\"; " +
            "filename=\"test-file\"\r\n" +
        "Content-Type: text/plain; charset=US-ASCII\r\n" +
        "Content-Transfer-Encoding: binary\r\n" +
        "\r\n" +
        "some random whatever\r\n" +
        "--foo\r\n" +
        "Content-Disposition: form-data; name=\"field3\"; " +
            "filename=\"file.tmp\"\r\n" +
        "Content-Type: application/octet-stream\r\n" +
        "Content-Transfer-Encoding: binary\r\n" +
        "\r\n" +
        "some random whatever\r\n" +
        "--foo--\r\n";
    final String s = out.toString("UTF-8");
    Assert.assertEquals(expected, s);
    Assert.assertEquals(-1, multipart.getTotalLength());
}
项目:purecloud-iot    文件:TestMultipartForm.java   
@Test
public void testMultipartFormBrowserCompatibleNonASCIIHeaders() throws Exception {
    final String s1 = constructString(SWISS_GERMAN_HELLO);
    final String s2 = constructString(RUSSIAN_HELLO);

    tmpfile = File.createTempFile("tmp", ".bin");
    final Writer writer = new FileWriter(tmpfile);
    try {
        writer.append("some random whatever");
    } finally {
        writer.close();
    }

    @SuppressWarnings("resource")
    final FormBodyPart p1 = FormBodyPartBuilder.create(
            "field1",
            new InputStreamBody(new FileInputStream(tmpfile), s1 + ".tmp")).build();
    @SuppressWarnings("resource")
    final FormBodyPart p2 = FormBodyPartBuilder.create(
            "field2",
            new InputStreamBody(new FileInputStream(tmpfile), s2 + ".tmp")).build();
    final HttpBrowserCompatibleMultipart multipart = new HttpBrowserCompatibleMultipart(
            Consts.UTF_8, "foo",
            Arrays.asList(p1, p2));

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    multipart.writeTo(out);
    out.close();

    final String expected =
        "--foo\r\n" +
        "Content-Disposition: form-data; name=\"field1\"; " +
            "filename=\"" + s1 + ".tmp\"\r\n" +
        "Content-Type: application/octet-stream\r\n" +
        "\r\n" +
        "some random whatever\r\n" +
        "--foo\r\n" +
        "Content-Disposition: form-data; name=\"field2\"; " +
            "filename=\"" + s2 + ".tmp\"\r\n" +
        "Content-Type: application/octet-stream\r\n" +
        "\r\n" +
        "some random whatever\r\n" +
        "--foo--\r\n";
    final String s = out.toString("UTF-8");
    Assert.assertEquals(expected, s);
    Assert.assertEquals(-1, multipart.getTotalLength());
}
项目:Kaspar    文件:UploadRequest.java   
public UploadRequest(String filename, InputStream in, String text, String comment){
    setProperty("filename", filename);
    setProperty("text", text);
    setProperty("file", new InputStreamBody(in, filename));
    setProperty("comment", comment);
}