当前位置: 首页>>代码示例>>Java>>正文


Java ByteArrayBody类代码示例

本文整理汇总了Java中org.apache.http.entity.mime.content.ByteArrayBody的典型用法代码示例。如果您正苦于以下问题:Java ByteArrayBody类的具体用法?Java ByteArrayBody怎么用?Java ByteArrayBody使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ByteArrayBody类属于org.apache.http.entity.mime.content包,在下文中一共展示了ByteArrayBody类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: uploadFile

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
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);
		}
	}
 
开发者ID:cytomine,项目名称:Cytomine-java-client,代码行数:19,代码来源:Cytomine.java

示例2: genContent

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
/**
 * 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");
}
 
开发者ID:rhli,项目名称:hadoop-EAR,代码行数:26,代码来源:TestJournalNodeImageManifest.java

示例3: put2

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
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();
    }
 
开发者ID:cytomine,项目名称:Cytomine-client-autobuilder,代码行数:27,代码来源:HttpClient.java

示例4: formatBinary

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
@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()));
        }
    }
}
 
开发者ID:opendatakit,项目名称:aggregate,代码行数:22,代码来源:OhmageJsonElementFormatter.java

示例5: login

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
@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.");
    }
}
 
开发者ID:ow2-proactive,项目名称:scheduling,代码行数:24,代码来源:LoginWithCredentialsCommand.java

示例6: testLoginWithCredentials

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
@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);
}
 
开发者ID:ow2-proactive,项目名称:scheduling,代码行数:27,代码来源:RestSchedulerJobTaskTest.java

示例7: doPostMultipart

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
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);
}
 
开发者ID:WASdev,项目名称:tool.lars,代码行数:17,代码来源:RepositoryContext.java

示例8: setTf

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
/**
 * 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);
  }
}
 
开发者ID:Idilia,项目名称:idilia-java-sdk,代码行数:28,代码来源:TaggingMenuRequest.java

示例9: testFileUpload

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
@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);
}
 
开发者ID:learning-layers,项目名称:LivingDocumentsServer,代码行数:27,代码来源:DocumentControllerIntegrationTest.java

示例10: saveScreenShot

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
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);
}
 
开发者ID:noveogroup,项目名称:clap,代码行数:21,代码来源:ClapApi.java

示例11: request

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
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);
}
 
开发者ID:rcarz,项目名称:jira-client,代码行数:27,代码来源:RestClient.java

示例12: sendBytes

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:k-int,项目名称:ECKClient,代码行数:35,代码来源:ClientHTTP.java

示例13: request_Member_modMemberPicture

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
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);
}
 
开发者ID:xxx4u,项目名称:kidsm_for_android,代码行数:18,代码来源:NetworkActivity.java

示例14: saveBotCam

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
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;
}
 
开发者ID:corydissinger,项目名称:mtgo-best-bot,代码行数:35,代码来源:BotCameraService.java

示例15: constructContentBody

import org.apache.http.entity.mime.content.ByteArrayBody; //导入依赖的package包/类
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);
            }
        }
    }
 
开发者ID:Axway,项目名称:ats-framework,代码行数:25,代码来源:HttpBodyPart.java


注:本文中的org.apache.http.entity.mime.content.ByteArrayBody类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。