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

项目:hadoop-EAR    文件:TestJournalNodeImageManifest.java   
/**
 * Generate random contents for the image and store it together with the md5
 * for later comparison.
 */
private ContentBody genContent(long txid) throws IOException {
  MessageDigest digester = MD5Hash.getDigester();

  // write through digester so we can roll the written image
  ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
  DigestOutputStream ds = new DigestOutputStream(bos, digester);

  // generate random bytes
  new Random().nextBytes(randomBytes);
  ds.write(randomBytes);
  ds.flush();

  // get written hash
  MD5Hash hash = new MD5Hash(digester.digest());

  // store contents and digest
  digests.put(txid, hash);
  content.put(txid, Arrays.copyOf(randomBytes, randomBytes.length));

  return new ByteArrayBody(bos.toByteArray(), "filename");
}
项目:Cytomine-client-autobuilder    文件:HttpClient.java   
public int put2(byte[] data) throws Exception {
        log.debug("Put " + URL.getPath());
        HttpPut httpPut = new HttpPut(URL.getPath());
        if (isAuthByPrivateKey) httpPut.setHeaders(headersArray);
        log.debug("Put send :" + data.length);

//        InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(data), data.length);
//        reqEntity.setContentType("binary/octet-stream");
//        reqEntity.setChunked(false);
//
//        BufferedHttpEntity myEntity = null;
//                   try {
//                       myEntity = new BufferedHttpEntity(reqEntity);
//                   } catch (IOException e) {
//                       // TODO Auto-generated catch block
//                       e.printStackTrace();
//                   }
        MultipartEntity myEntity = new MultipartEntity();
        myEntity.addPart("files[]",new ByteArrayBody(data,"toto")) ;
        //int code = client.post(entity);


        httpPut.setEntity(myEntity);
        response = client.execute(targetHost, httpPut, localcontext);
        return response.getStatusLine().getStatusCode();
    }
项目:aggregate    文件:OhmageJsonElementFormatter.java   
@Override
public void formatBinary(BlobSubmissionType blobSubmission,
        FormElementModel element, String ordinalValue, Row row,
        CallingContext cc) throws ODKDatastoreException {
    if (!(blobSubmission == null
            || (blobSubmission.getAttachmentCount(cc) == 0) || (blobSubmission
                .getContentHash(1, cc) == null))) {
        byte[] imageBlob = null;
        if (blobSubmission.getAttachmentCount(cc) == 1) {
            imageBlob = blobSubmission.getBlob(1, cc);
        }
        if (imageBlob != null && imageBlob.length > 0) {
            UUID photoUUID = UUID.randomUUID();
            OhmageJsonTypes.photo photo = new OhmageJsonTypes.photo(
                    element.getElementName(), photoUUID);
            responses.add(photo);
            photos.put(photoUUID,
            new ByteArrayBody(imageBlob, ContentType.create(blobSubmission.getContentType(1, cc)), photoUUID.toString()));
        }
    }
}
项目:Cytomine-java-client    文件:Cytomine.java   
public void uploadFile(String url, byte[] data) throws CytomineException {

        try {
            HttpClient client = null;
            MultipartEntity entity = new MultipartEntity();
            entity.addPart("files[]", new ByteArrayBody(data, new Date().getTime() + "file"));
            client = new HttpClient(publicKey, privateKey, getHost());
            client.authorize("POST", url, entity.getContentType().getValue(), "application/json,*/*");
            client.connect(getHost() + url);
            int code = client.post(entity);
            String response = client.getResponseData();
            log.debug("response=" + response);
            client.disconnect();
            JSONObject json = createJSONResponse(code, response);
        } catch (IOException e) {
            throw new CytomineException(e);
        }
    }
项目:scheduling    文件:LoginWithCredentialsCommand.java   
@Override
protected String login(ApplicationContext currentContext) throws CLIException {
    File credentials = new File(pathname);
    if (!credentials.exists()) {
        throw new CLIException(REASON_INVALID_ARGUMENTS,
                               String.format("File does not exist: %s", credentials.getAbsolutePath()));
    }
    if (warn) {
        writeLine(currentContext, "Using the default credentials file: %s", credentials.getAbsolutePath());
    }
    HttpPost request = new HttpPost(currentContext.getResourceUrl("login"));
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("credential",
                   new ByteArrayBody(FileUtility.byteArray(credentials), APPLICATION_OCTET_STREAM.getMimeType()));
    request.setEntity(entity);
    HttpResponseWrapper response = execute(request, currentContext);
    if (statusCode(OK) == statusCode(response)) {
        return StringUtility.responseAsString(response).trim();
    } else {
        handleError("An error occurred while logging: ", response, currentContext);
        throw new CLIException(REASON_OTHER, "An error occurred while logging.");
    }
}
项目:scheduling    文件:RestSchedulerJobTaskTest.java   
@Test
public void testLoginWithCredentials() throws Exception {
    RestFuncTestConfig config = RestFuncTestConfig.getInstance();
    Credentials credentials = RestFuncTUtils.createCredentials(config.getLogin(),
                                                               config.getPassword(),
                                                               RestFuncTHelper.getSchedulerPublicKey());
    String schedulerUrl = getResourceUrl("login");
    HttpPost httpPost = new HttpPost(schedulerUrl);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                                                                          .addPart("credential",
                                                                                   new ByteArrayBody(credentials.getBase64(),
                                                                                                     ContentType.APPLICATION_OCTET_STREAM,
                                                                                                     null));
    httpPost.setEntity(multipartEntityBuilder.build());
    HttpResponse response = executeUriRequest(httpPost);
    assertHttpStatusOK(response);
    String sessionId = assertContentNotEmpty(response);

    String currentUserUrl = getResourceUrl("logins/sessionid/" + sessionId);

    HttpGet httpGet = new HttpGet(currentUserUrl);
    response = executeUriRequest(httpGet);
    assertHttpStatusOK(response);
    String userName = assertContentNotEmpty(response);
    Assert.assertEquals(config.getLogin(), userName);
}
项目:tool.lars    文件:RepositoryContext.java   
public String doPostMultipart(String url,
                              String name,
                              String json,
                              byte[] content,
                              ContentType contentType,
                              int expectedStatusCode)
        throws ClientProtocolException, IOException {
    HttpPost post = new HttpPost(fullURL + url);
    HttpEntity requestEntity = MultipartEntityBuilder.create()
            .addPart("attachmentInfo", new StringBody(json, ContentType.APPLICATION_JSON))
            .addPart(name, new ByteArrayBody(content, contentType, name))
            .build();
    post.setEntity(requestEntity);

    return doRequest(post, expectedStatusCode);
}
项目:idilia-java-sdk    文件:TaggingMenuRequest.java   
/**
 * Provide the sense inventory of the tagging menu using a disambiguation result.
 * @param tf a disambiguate result with resultMime application/x-tf+xml or application/x-tf+xml+gz
 * @return updated TaggingMenuRequest
 * @throws IdiliaClientException when the disambiguated result cannot be extracted
 */
@JsonIgnore
public final TaggingMenuRequest setTf(DisambiguatedDocument tf) throws IdiliaClientException {
  try {
    byte[] bytes = IOUtils.toByteArray(tf.getEncodedInputStream());
    // Work around the MultipartEntityBuilder inability for us to add a form
    // with Content-Encoding set. Therefore we ensure that we communicate 
    // the encoding through the Content-Type.
    String resultMime = tf.getResultMime();
    ContentType ct = null;
    if (tf.getEncoding() != null && tf.getEncoding().contentEquals("gzip")) {
      if (!resultMime.endsWith("+gz"))
        resultMime += "+gz";
      ct = ContentType.create(resultMime);
    } else
      ct = ContentType.create(resultMime, Consts.UTF_8);
    this.tf = new ByteArrayBody(bytes, ct, "tf");
    return this;
  } catch (IOException ioe) {
    throw new IdiliaClientException(ioe);
  }
}
项目:LivingDocumentsServer    文件:DocumentControllerIntegrationTest.java   
@Test
public void testFileUpload() throws Exception {
    //Add document
    HttpResponse responseCreateDocument = UserSession.user().post(RESOURCE_DOCUMENT, document);
    Document respondedDocument = ResponseHelper.getBody(responseCreateDocument, Document.class);
    Assert.assertNotNull(respondedDocument);

    //load file
    String fileName = "sandbox.pdf";
    InputStream in = null;
    byte[] source = null;
    try {
        in = UserSession.class.getResourceAsStream("/" + fileName);
        source = IOUtils.toByteArray(in);
    } finally {
        IOUtils.closeQuietly(in);
    }
    ByteArrayBody fileBody = new ByteArrayBody(source, fileName);

    //Add document
    System.out.println(RESOURCE_DOCUMENT + "/upload?documentId=" + respondedDocument.getId());
    HttpResponse responseUploadAttachment = UserSession.user().postFile(RESOURCE_DOCUMENT + "/upload?documentId=" + respondedDocument.getId(), fileBody);
    Assert.assertEquals(HttpStatus.OK, ResponseHelper.getStatusCode(responseUploadAttachment));
    Long attachmentId = ResponseHelper.getBody(responseUploadAttachment, Long.class);
    Assert.assertNotNull(attachmentId);
}
项目:clap    文件:ClapApi.java   
public void saveScreenShot(Bitmap bitmap) throws IOException {
    BasicHttpParams params = getBasicHttpParams();

    String url = getBuildConfigField(BuildConfigHelper.FIELD_CLAP_SERVER_URL) + "/upload/screenshot";
    String token = getToken(params);
    String revisionHash = getBuildConfigField(BuildConfigHelper.FIELD_CLAP_SOURCE_HASH);

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 50, output);
    byte[] bitmapBytes = output.toByteArray();

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("token", new StringBody(token));
    multipartEntity.addPart("revisionHash", new StringBody(revisionHash));
    multipartEntity.addPart("screenshotFile", new ByteArrayBody(bitmapBytes, "screen.png"));
    post.setEntity(multipartEntity);
    client.execute(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);
}
项目:ECKClient    文件:ClientHTTP.java   
/**
 * Performs a HTTP PUT to send the supplied data to the given path
 * 
 * @param path The URL / Path of where the data needs to be sent
 * @param xmlData An array of xml files that are to be sent
 * @param zipData An array of zip files that are to be sent
 * @param attributes An array of attribute name / value pairs that need to be added to the path 
 * @param acceptableResponseContentType The type of content we expect to be returned
 * 
 * @return A HttpResult object that can be interrogated to see if the call was successful or not
 */
static public HttpResult sendBytes(String path, ArrayList<byte[]> xmlData, ArrayList<byte[]> zipData, ArrayList<BasicNameValuePair> attributes, ContentType acceptableResponseContentType) {
    HttpResult result = new HttpResult();

    MultipartEntity requestEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);;
       int filenameCount = 1;

    if (xmlData != null) {
        for (byte[] xmlBytes : xmlData) {
            requestEntity.addPart(getFileParameterName(false, filenameCount), new ByteArrayBody(xmlBytes, CONTENT_TYPE_APPLICATION_XML.toString(), FILENAME_PREFIX + filenameCount));
            filenameCount++;
        }
    }

    if (zipData != null) {
        for (byte[] zipBytes : zipData) {
            requestEntity.addPart(getFileParameterName(true, filenameCount), new ByteArrayBody(zipBytes, CONTENT_TYPE_APPLICATION_ZIP.getMimeType(), FILENAME_PREFIX + filenameCount));
            filenameCount++;
        }
    }

    result = send(path, requestEntity, attributes, acceptableResponseContentType);
    return(result);
}
项目:kidsm_for_android    文件:NetworkActivity.java   
public void request_Member_modMemberPicture(String member_srl, Bitmap member_picture) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    member_picture.compress(Bitmap.CompressFormat.JPEG, 100, baos);
       ByteArrayBody bab = new ByteArrayBody(baos.toByteArray(), "image.jpg");

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
       try {
        reqEntity.addPart("member_srl", new StringBody(member_srl));
        reqEntity.addPart("member_picture", bab);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

       PUT_IMAGE("Member/modMemberPicture", reqEntity);
}
项目:mtgo-best-bot    文件:BotCameraService.java   
public Long saveBotCam(BotCamera botCamera) {
    HttpEntity entity = MultipartEntityBuilder
            .create()
            .addPart("file", new ByteArrayBody(botCamera.getScreenShot(), "botSnapshot"))
            .build();

    Long idResponse = -1L;

    try {
        HttpPost httpPost = new HttpPost(apiUrl + BotCameraController.ENDPOINT_ROINT + "/" + botCamera.getPlayerBot().getName());
        httpPost.setEntity(entity);
        HttpResponse response = uploadHttpClient.execute(httpPost);
        ResponseHandler<String> handler = new BasicResponseHandler();

        if(response != null &&
            response.getStatusLine() != null &&
            response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {

            final String rawResult = handler.handleResponse(response);

            idResponse = Long.parseLong(rawResult);
        } else {
            log.error("Failed to upload pictar!");
            log.error("Headers received: " + Arrays.stream(response.getAllHeaders()).map(header -> new String(header.getName() + ": " + header.getValue()))
                                                                                    .reduce("", (result, next) -> System.lineSeparator() + next));
            log.error("Body received: " + System.lineSeparator() + handler.handleResponse(response));
        }
    } catch (IOException e) {
        log.error("Failed to upload pictar!");
        log.error(e.getMessage());
    }

    return idResponse;
}
项目:ats-framework    文件:HttpBodyPart.java   
ContentBody constructContentBody() throws UnsupportedEncodingException {

        ContentType contentTypeObject = constructContentTypeObject();

        if (filePath != null) { // FILE part
            if (contentTypeObject != null) {
                return new FileBody(new File(filePath), contentTypeObject);
            } else {
                return new FileBody(new File(filePath));
            }
        } else if (content != null) { // TEXT part
            if (contentTypeObject != null) {
                return new StringBody(content, contentTypeObject);
            } else {
                return new StringBody(content, ContentType.TEXT_PLAIN);
            }
        } else { // BYTE ARRAY part
            if (contentTypeObject != null) {
                return new ByteArrayBody(this.fileBytes, contentTypeObject, fileName);
            } else {
                return new ByteArrayBody(this.fileBytes, fileName);
            }
        }
    }
项目:appez-android    文件:HttpUtility.java   
/**
 * Processes file upload information to extract the information regarding
 * the files from the device storage that needs to be uploaded to the remote
 * server
 * 
 * @param postRequest
 *            : {@link HttpPost} request object
 * 
 * */
private MultipartEntity processFileUploadInfo(HttpPost postRequest) {
    String fileUploadInfo = this.requestFileUploadInfo;
    MultipartEntity fileUploadEntity = new MultipartEntity();
    try {
        // Here we are receiving the JSONArray
        JSONArray fileInformation = new JSONArray(fileUploadInfo);
        Log.d(SmartConstants.APP_NAME, "HttpUtility->processFileUploadInfo->file information:" + fileUploadInfo);
        int totalFilesToUpload = fileInformation.length();
        for (int currentIndex = 0; currentIndex < totalFilesToUpload; currentIndex++) {
            // add the file entry to the 'MultipartEntity'
            String fileToUploadType = fileInformation.getJSONObject(currentIndex).getString("imageType");
            Log.d(SmartConstants.APP_NAME, "HttpUtility->processFileUploadInfo->fileToUploadType:" + fileToUploadType);
            if (fileToUploadType.equalsIgnoreCase(SmartConstants.FILE_UPLOAD_TYPE_URL)) {
                String filenameToUpload = fileInformation.getJSONObject(currentIndex).getString("imageData");
                Log.d(SmartConstants.APP_NAME, "HttpUtility->processFileUploadInfo->fileToUpload:" + filenameToUpload);
                if (filenameToUpload.contains("file://")) {
                    filenameToUpload = filenameToUpload.replace("file://", "");
                }
                Log.d(SmartConstants.APP_NAME, "HttpUtility->processFileUploadInfo->NEW fileToUpload:" + filenameToUpload);
                File fileToUpload = new File(filenameToUpload);
                FileBody fileBody = new FileBody(fileToUpload);
                fileUploadEntity.addPart(fileInformation.getJSONObject(currentIndex).getString("name"), fileBody);
            } else if (fileToUploadType.equalsIgnoreCase(SmartConstants.FILE_UPLOAD_TYPE_DATA)) {
                // TODO need to add handling for Base64 content uploading
                byte[] fileContent = Base64.decode(fileInformation.getJSONObject(currentIndex).getString("imageData"), Base64.DEFAULT);
                ByteArrayBody fileByteArrayBody = new ByteArrayBody(fileContent, null);
                fileUploadEntity.addPart(fileInformation.getJSONObject(currentIndex).getString("name"), fileByteArrayBody);
            }
        }
    } catch (JSONException je) {
        // TODO need to handle this exception
        Log.d(SmartConstants.APP_NAME, "HttpUtility->processFileUploadInfo->JSONException:" + je.getMessage());
    } catch (Exception e) {
        Log.d(SmartConstants.APP_NAME, "HttpUtility->processFileUploadInfo->Exception:" + e.getMessage());
    }
    return fileUploadEntity;
}
项目:meituanwaimai-sdk    文件:BaseServiceImpl.java   
private JSONObject getResponseJsonObject(String httpMethod, String url, Object params, String imageName, byte[] fileData) throws IOException, MtWmErrorException {

        String fullUrl = getBaseApiUrl() + url;

        List<NameValuePair> sysNameValuePairs = getSysNameValuePairs(fullUrl, params);
        List<NameValuePair> nameValuePairs = getNameValuePairs(params);
        HttpPost httpPost = new HttpPost(fullUrl + "?" + URLEncodedUtils.format(sysNameValuePairs, UTF_8));

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (NameValuePair p : nameValuePairs) {
            builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset(UTF_8));
        }

        builder.addPart("img_data", new ByteArrayBody(fileData, imageName));

        final HttpEntity entity = builder.build();
        httpPost.addHeader(entity.getContentType());
        httpPost.setEntity(entity);


        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        String resultContent = new BasicResponseHandler().handleResponse(response);
        JSONObject jsonObject = JSON.parseObject(resultContent);
        MtWmError error = MtWmError.fromJson(jsonObject);
        if (error != null) {
            logging(url, httpMethod, false, httpPost.getURI() + "\nBody:" + JSON.toJSONString(params), resultContent);
            throw new MtWmErrorException(error.getErrorCode(), error.getErrorMsg());
        }
        logging(url, httpMethod, true, httpPost.getURI() + "\nBody:" + JSON.toJSONString(params), resultContent);
        return jsonObject;
    }
项目:hadoop-EAR    文件:HttpImageUploadChannel.java   
/**
 * Create a post request encapsulating bytes from the given
 * ByteArrayOutputStream.
 */
private HttpPost setupRequest(ByteArrayOutputStream bos) {
  ContentBody cb = new ByteArrayBody(bos.toByteArray(), "image");
  HttpPost postRequest = new HttpPost(uri + "/uploadImage");
  MultipartEntity reqEntity = new MultipartEntity(
      HttpMultipartMode.BROWSER_COMPATIBLE);

  // add a single part to the request
  reqEntity.addPart("file", cb);
  postRequest.setEntity(reqEntity);

  return postRequest;
}
项目:sparkjava-spike    文件:ArticleApiTest.java   
@Test
    public void testMultipart() throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost createArticleRequest = new HttpPost("http://localhost:" + port + "/articles");
            String articleAsString = objectMapper.writeValueAsString(new Article("article title", "article body"));
            String imagePartName = "image";
            String imageFileName = "image.jpg";
            byte[] imageBytes = IOUtils.toByteArray(getClass().getResourceAsStream("/" + imageFileName));
            HttpEntity requestEntity = MultipartEntityBuilder.create()
                    .addTextBody("article", articleAsString, ContentType.APPLICATION_JSON)
                    .addPart(FormBodyPartBuilder.create()
                            .setName(imagePartName)
                            .setBody(new ByteArrayBody(imageBytes, ContentType.create("image/jpeg"), imageFileName))
                            .setField("Content-Disposition", String.format("form-data; name=\"%s\"; filename=\"%s\"; size=%d", imagePartName, imageFileName, imageBytes.length))
                            .build())
                    .build();
            createArticleRequest.setEntity(requestEntity);
            try (CloseableHttpResponse createArticleResponse = httpClient.execute(createArticleRequest)) {
                assertThat(createArticleResponse.getStatusLine().getStatusCode(), equalTo(201));
                String location = createArticleResponse.getFirstHeader("location").getValue();
//                System.out.println("Retrieving article from: " + location);
                HttpGet getArticleRequest = new HttpGet(location);
                try (CloseableHttpResponse getArticleResponse = httpClient.execute(getArticleRequest)) {
                    assertThat(getArticleResponse.getStatusLine().getStatusCode(), equalTo(200));
                    assertThat(getArticleResponse.getFirstHeader("content-type").getValue(), equalTo("application/json"));
                }
                String imageUrl = location + "/images/" + imageFileName;
//                System.out.println("Retrieving image from:   " + imageUrl);
                HttpGet getImageRequest = new HttpGet(imageUrl);
                try (CloseableHttpResponse getImageResponse = httpClient.execute(getImageRequest)) {
                    assertThat(getImageResponse.getStatusLine().getStatusCode(), equalTo(200));
                    assertThat(getImageResponse.getFirstHeader("content-type").getValue(), equalTo("image/jpeg"));
                    assertThat(IOUtils.toByteArray(getImageResponse.getEntity().getContent()), equalTo(imageBytes));
                }
            }
        }
    }
项目:scheduling-portal    文件:SchedulerServiceImpl.java   
private MultipartEntity createLoginPasswordSSHKeyMultipart(String login, String pass, String ssh)
        throws UnsupportedEncodingException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("username", new StringBody(login));
    entity.addPart("password", new StringBody(pass));

    if (ssh != null && !ssh.isEmpty()) {
        entity.addPart("sshKey", new ByteArrayBody(ssh.getBytes(), MediaType.APPLICATION_OCTET_STREAM, null));
    }

    return entity;
}
项目:scheduling-portal    文件:RMServiceImpl.java   
private MultipartEntity createLoginPasswordSSHKeyMultipart(String login, String pass, String ssh)
        throws UnsupportedEncodingException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("username", new StringBody(login));
    entity.addPart("password", new StringBody(pass));
    if (ssh != null && !ssh.isEmpty()) {
        entity.addPart("sshKey", new ByteArrayBody(ssh.getBytes(), MediaType.APPLICATION_OCTET_STREAM, null));
    }
    return entity;
}
项目:EasyLinkNJ    文件:HttpTaskUtil.java   
private static void setByteArrayBodyToMultipartEntity(MultipartEntity me, List<NameByteValuePair> params) throws UnsupportedEncodingException{

    if(params == null || params.size() == 0)
        return;

    NameByteValuePair nbvp = null;
    for(int i=0; i<params.size(); i++){
        nbvp = params.get(i);
        me.addPart(nbvp.getName(), new ByteArrayBody(nbvp.getData(), nbvp.getName()));
    }
}
项目:LivingDocumentsServer    文件:DocumentControllerIntegrationTest.java   
@Test
public void testFileDownload() throws Exception {

    //Add document
    HttpResponse responseCreateDocument = UserSession.user().post(RESOURCE_DOCUMENT, document);
    Document respondedDocument = ResponseHelper.getBody(responseCreateDocument, Document.class);
    Assert.assertNotNull(respondedDocument);

    //load file
    String fileName = "sandbox.pdf";
    InputStream in = null;
    byte[] source = null;
    try {
        in = UserSession.class.getResourceAsStream("/" + fileName);
        source = IOUtils.toByteArray(in);
    } finally {
        IOUtils.closeQuietly(in);
    }
    ByteArrayBody fileBody = new ByteArrayBody(source, fileName);

    //Add document
    System.out.println(RESOURCE_DOCUMENT + "/upload?documentId=" + respondedDocument.getId());
    HttpResponse responseUploadAttachment = UserSession.user().postFile(RESOURCE_DOCUMENT + "/upload?documentId=" + respondedDocument.getId(), fileBody);
    Assert.assertEquals(HttpStatus.OK, ResponseHelper.getStatusCode(responseUploadAttachment));
    Long attachmentId = ResponseHelper.getBody(responseUploadAttachment, Long.class);
    Assert.assertNotNull(attachmentId);

    String uri = RESOURCE_DOCUMENT+"/"+ respondedDocument.getId()+"/download/" + attachmentId;
    HttpResponse response = UserSession.user().get(uri);
    Assert.assertEquals(HttpStatus.OK, ResponseHelper.getStatusCode(response));

    HttpEntity entity = response.getEntity();
    System.out.println(entity.getContentType());
    InputStream inStream = entity.getContent();
    InputStream inStreamExistingFile = new FileInputStream("./src/test/resources/sandbox.pdf");
    Assert.assertNotNull(inStream);
    Assert.assertNotNull(inStreamExistingFile);
    Assert.assertTrue(IOUtils.contentEquals(inStream, inStreamExistingFile));
}
项目:LivingDocumentsServer    文件:UserSession.java   
public HttpResponse postFile(String url, ByteArrayBody body) throws Exception {

        CloseableHttpClient httpclient = getClient();
        HttpPost httppost = new HttpPost(endpoint + url);

        //FileBody bin = new FileBody(new File(args[0]));
        //StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("file", body)
                        //.addPart("comment", comment)
                .build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        /*try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }*/
        return httpclient.execute(httppost);
    }
项目:shogun2    文件:HttpUtil.java   
/**
 *
 * @param uri The URI to POSt to
 * @param parts {@link Part}s of FormMultipartRequest
 * @param headersToForward  Should headers of request should be forwarded
 * @return The HTTP response as Response object.
 * @throws IOException
 * @throws URISyntaxException
 * @throws HttpException
 */
private static Response postMultiPart(URI uri, Collection<Part> parts, Header[] headersToForward) throws IOException, URISyntaxException, HttpException {

    HttpPost httpPost = new HttpPost(uri);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    for (Part part: parts) {
        String name = part.getName();
        String fileName = part.getSubmittedFileName();

        // we should use a ByteArrayBody instead of InputStreamBody!
        // when using InputStreamBody, the HttpClient lib will use chunked encoding,
        // which is not supported by all servers.
        // by using the ByteArrayBody, the size of the content is known and the lib
        // will NOT use chunked encoding, but add a content-length header instead.
        byte[] data = IOUtils.toByteArray(part.getInputStream());
        final ContentType contentType = ContentType.create(part.getContentType());

        ByteArrayBody byteArrayBody = new ByteArrayBody(data, contentType, fileName);

        // add the part
        builder.addPart(name, byteArrayBody);

        LOG.debug("Add a form/multipart part with name '" + name + "', content type '" + contentType.getMimeType() + "' and size "
                + part.getSize());
    }

    HttpEntity multiPartEntity = builder.build();

    httpPost.setEntity(multiPartEntity);

    return send(httpPost, null, headersToForward);
}
项目: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;
}
项目:sana.mobile    文件:MDSInterface.java   
/**
 * Executes an Http POST call with a binary chunk as a file
 *
 * @param c the current context
 * @param savedProcedureId The encounter id
 * @param elementId the observation id
 * @param fileGuid the unique id of the file
 * @param type the observation type
 * @param fileSize total byte count
 * @param start offset from 0 of this chunk
 * @param end offset + size
 * @param byte_data the binary chunk that is being sent
 * @return true if successful
 * @throws UnsupportedEncodingException
 */
private static boolean postBinaryAsFile(Context c, String savedProcedureId,
        String elementId, String fileGuid, ElementType type, int fileSize,
        int start, int end, byte byte_data[]) throws UnsupportedEncodingException
{
    SharedPreferences preferences =
        PreferenceManager.getDefaultSharedPreferences(c);
    String mdsUrl = getMDSUrl(c);
    mdsUrl = checkMDSUrl(mdsUrl);
    String mUrl = constructBinaryChunkSubmitURL(mdsUrl);
    // this is the compat layer
    String gid = String.format("%s_%s", elementId, fileGuid);
    Log.d(TAG,"Posting to: " + mUrl);
    Log.d(TAG,"....file chunk: " + elementId +", guid:" + fileGuid);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("procedure_guid", new StringBody(savedProcedureId));
       entity.addPart("element_id", new StringBody(elementId));
       entity.addPart("binary_guid", new StringBody(fileGuid));
       entity.addPart("element_type", new StringBody(type.toString()));
       entity.addPart("file_size", new StringBody(Integer.toString(fileSize)));
       entity.addPart("byte_start", new StringBody(Integer.toString(start)));
       entity.addPart("byte_end", new StringBody(Integer.toString(end)));
       entity.addPart("byte_data", new ByteArrayBody(byte_data, type.getFilename()));

    //execute
    MDSResult postResponse = MDSInterface.doPost(c, mUrl, entity);
    return (postResponse != null)? postResponse.succeeded(): false;
}
项目:gocd    文件:HttpService.java   
public HttpEntity createMultipartRequestEntity(File artifact, Properties artifactChecksums) throws IOException {
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.addPart(GoConstants.ZIP_MULTIPART_FILENAME, new FileBody(artifact));
    if (artifactChecksums != null) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        artifactChecksums.store(outputStream, "");
        entityBuilder.addPart(GoConstants.CHECKSUM_MULTIPART_FILENAME, new ByteArrayBody(outputStream.toByteArray(), "checksum_file"));
    }
    return entityBuilder.build();
}
项目:VKOpenRobot    文件:VKConnectorImpl.java   
private UploadedPhoto uploadPhoto(String serverUrl, byte[] photo) throws IOException {
    HttpPost httppost = new HttpPost(serverUrl);
    MultipartEntity mpEntity = new MultipartEntity();

    ByteArrayBody byteArrayBody = new ByteArrayBody(photo, "photo.jpg");
    mpEntity.addPart("photo", byteArrayBody);

    httppost.setEntity(mpEntity);
    HttpResponse response = client.execute(httppost);
    String responseBody = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    log.debug(responseBody);

    return objectMapper.readValue(responseBody, UploadedPhoto.class);
}
项目:appengine-tck    文件:FileUploader.java   
public String uploadFile(String uri, String partName, String filename, String mimeType, byte[] contents, int expectedResponseCode) throws URISyntaxException, IOException {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost(uri);
        ByteArrayBody contentBody = new ByteArrayBody(contents, ContentType.create(mimeType), filename);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart(partName, contentBody);
        post.setEntity(builder.build());
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(String.format("Invalid response code, %s", statusCode), expectedResponseCode, statusCode);
        return result;
    }
}
项目:dtgov    文件:Multipart.java   
public void post(HttpClient httpclient, URI uri, Map<String,Object> parameters) throws IOException, WorkflowException {
    MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    for (String key : parameters.keySet()) {
        ContentBody content = null;
        Object param = parameters.get(key);
        if (param instanceof String) {
            StringBody stringBody = new StringBody((String) param, "text/plain", Charset.forName("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
            content = stringBody;
        } else {
            //turn object into byteArray, or it also supports InputStreamBody or FileBody
            ByteArrayBody byteBody = new ByteArrayBody(null, key);
            content = byteBody;
        }
        multiPartEntity.addPart(key, content);
    }
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(multiPartEntity);
    HttpResponse response = httpclient.execute(httpPost);
    InputStream is = response.getEntity().getContent();
    String responseStr = IOUtils.toString(is);
    if (response.getStatusLine().getStatusCode()==200 || response.getStatusLine().getStatusCode()==201) {
        logger.debug(responseStr);
    } else {
        throw new WorkflowException("Workflow ERROR - HTTP STATUS CODE " + response.getStatusLine().getStatusCode() + ". "  //$NON-NLS-1$ //$NON-NLS-2$
                + response.getStatusLine().getReasonPhrase() + ". " + responseStr); //$NON-NLS-1$
    }
    is.close();
}
项目:jslicify    文件:MediaFireClient.java   
/**
 * Upload a byte[] to mediafire, creating a new file with the specified filename. 
 * 
 * @param fileName The file name to create on mediafire.
 * @param data The contents of the file
 * @throws IOException
 */
public void upload(String fileName, byte[] data) throws IOException
{
    String targetURL = HTTP_MEDIAFIRE_BASE_API + "upload/upload.php?session_token=" + SessionToken;

    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(targetURL);

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new ByteArrayBody(data, fileName);
    mpEntity.addPart("myFile", cbFile);


    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
        EntityUtils.consume(resEntity);
    }

    httpclient.getConnectionManager().shutdown();

}
项目:kidsm_for_android    文件:NetworkActivity.java   
public void request_Album_setPhoto(String album_srl, String member_srl, String photo_message, String photo_tag, String photo_private, Bitmap photo) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//      byte[] imageBytes = baos.toByteArray();
//      String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        ByteArrayBody bab = new ByteArrayBody(baos.toByteArray(), "image.jpg");


        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        try {
            reqEntity.addPart("album_srl", new StringBody(album_srl));
            reqEntity.addPart("member_srl", new StringBody(member_srl));
            reqEntity.addPart("photo_message", new StringBody(URLEncoder.encode(photo_message, HTTP.UTF_8)));
            reqEntity.addPart("photo_tag", new StringBody(photo_tag));
            reqEntity.addPart("photo_private", new StringBody(photo_private));
            reqEntity.addPart("photo", bab);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



//      List<NameValuePair> params = new ArrayList<NameValuePair>();
//      params.add(new BasicNameValuePair("album_srl", album_srl));
//      params.add(new BasicNameValuePair("member_srl", member_srl));
//      params.add(new BasicNameValuePair("photo_tag", photo_tag));
//      params.add(new BasicNameValuePair("photo_private", photo_private));
//      
//      ByteArrayOutputStream baos = new ByteArrayOutputStream();
//      photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//      byte[] imageBytes = baos.toByteArray();
//      String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
//      params.add(new BasicNameValuePair("photo", encodedImage));
        POST_IMAGE("Album/setPhoto", reqEntity);
    }
项目:kidsm_for_android    文件:NetworkActivityWithSliding.java   
public void request_Album_setPhoto(String album_srl, String member_srl, String photo_message, String photo_tag, String photo_private, Bitmap photo) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//      byte[] imageBytes = baos.toByteArray();
//      String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        ByteArrayBody bab = new ByteArrayBody(baos.toByteArray(), "image.jpg");


        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        try {
            reqEntity.addPart("album_srl", new StringBody(album_srl));
            reqEntity.addPart("member_srl", new StringBody(member_srl));
            reqEntity.addPart("photo_message", new StringBody(URLEncoder.encode(photo_message, HTTP.UTF_8)));
            reqEntity.addPart("photo_tag", new StringBody(photo_tag));
            reqEntity.addPart("photo_private", new StringBody(photo_private));
            reqEntity.addPart("photo", bab);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



//      List<NameValuePair> params = new ArrayList<NameValuePair>();
//      params.add(new BasicNameValuePair("album_srl", album_srl));
//      params.add(new BasicNameValuePair("member_srl", member_srl));
//      params.add(new BasicNameValuePair("photo_tag", photo_tag));
//      params.add(new BasicNameValuePair("photo_private", photo_private));
//      
//      ByteArrayOutputStream baos = new ByteArrayOutputStream();
//      photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//      byte[] imageBytes = baos.toByteArray();
//      String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
//      params.add(new BasicNameValuePair("photo", encodedImage));
        POST_IMAGE("Album/setPhoto", reqEntity);
    }
项目:BigFileUploadJava    文件:ApacheHCUploader.java   
@Override
public void upload(Part part) {

    String partName = part.getName();
    Map<String, ContentBody> params = new HashMap<String, ContentBody>();
    params.put(Config.keyFile, new ByteArrayBody(part.getContent(), partName));
    post(params);
    log.debug(partName + " uploaded.");
}
项目:sonar-issueresolver-plugin    文件:PluginIT.java   
private String importResolvedIssues(final String projectKey, final String data) {
    // Cannot use query because we use the fileupload
    LOGGER.info("Importing issues into project {}", projectKey);

    // Use httpclient 4
    final CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(Server.ADMIN_LOGIN, Server.ADMIN_PASSWORD));

    final AuthCache authCache = new BasicAuthCache();
    authCache.put(new HttpHost("localhost", orchestrator.getServer().port()), new BasicScheme());

    final HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

    final HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(provider);
    context.setAuthCache(authCache);

    final HttpPost post = new HttpPost(orchestrator.getServer().getUrl() + "/"
            + IssueResolverWebService.CONTROLLER_PATH + "/" + ImportAction.ACTION);
    post.setHeader("Accept", "application/json");

    // Set data
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("projectKey", new StringBody(projectKey, ContentType.MULTIPART_FORM_DATA));
    builder.addPart("data",
            new ByteArrayBody(data.getBytes(), ContentType.MULTIPART_FORM_DATA, "resolved-issues.json"));
    post.setEntity(builder.build());

    try {
        final HttpResponse response = client.execute(post, context);
        final HttpEntity entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return EntityUtils.toString(entity);
        } else {
            throw new ConnectionException("HTTP error: " + response.getStatusLine().getStatusCode() + ", msg: "
                    + response.getStatusLine().getReasonPhrase() + ", query: " + post.toString());
        }
    } catch (IOException e) {
        throw new ConnectionException("Query: " + post.getURI(), e);
    } finally {
        post.releaseConnection();
    }
}
项目:Java-APIs    文件:ClassificationClient.java   
private void addByteArray(Collection<FormBodyPart> parts, byte[] data, String fileName) {
    FormBodyPart filePart = new FormBodyPart("UploadFile", new ByteArrayBody(data, fileName));
    parts.add(filePart);
}
项目:java-restclient    文件:HTTPCPartVisitor.java   
@Override
public void visitByteArrayPart(ByteArrayPart part) {
    builder.addPart(part.getName(), new ByteArrayBody(part.getContent(), adaptContentType(part.getContentType()), part.getArrayName()));
}
项目:STAPI-Android    文件:STAPIParameters4Post.java   
public STAPIParameters4Post setFile(byte[] data) {
    multiPart.addPart("file", new ByteArrayBody(data, "NoName"));
    return this;
}
项目:weixin-mp-java-master    文件:WxMediaService.java   
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;
}