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

下面列出了怎么用org.apache.http.entity.mime.content.ByteArrayBody的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: 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);
            }
        }
    }
 
源代码2 项目: 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.");
    }
}
 
源代码3 项目: 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);
}
 
源代码4 项目: database   文件: TestMultipartContent.java
private HttpEntity getUpdateEntity() {
	final Random r = new Random();
	final byte[] data = new byte[256];
	
       final MultipartEntity entity = new MultipartEntity();
       r.nextBytes(data);
       entity.addPart(new FormBodyPart("remove", 
               new ByteArrayBody(
                       data, 
                       "application/xml", 
                       "remove")));
       r.nextBytes(data);
       entity.addPart(new FormBodyPart("add", 
               new ByteArrayBody(
                       data, 
                       "application/xml", 
                       "add")));
	
       return entity;
}
 
源代码5 项目: cxf   文件: Client.java
private static void uploadToCatalog(final String url, final CloseableHttpClient httpClient,
        final String filename) throws IOException {

    System.out.println("Sent HTTP POST request to upload the file into catalog: " + filename);

    final HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity();
    byte[] bytes = IOUtils.readBytesFromStream(Client.class.getResourceAsStream("/" + filename));
    entity.addPart(filename, new ByteArrayBody(bytes, filename));

    post.setEntity(entity);

    try {
        CloseableHttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() == 201) {
            System.out.println(response.getFirstHeader("Location"));
        } else if (response.getStatusLine().getStatusCode() == 409) {
            System.out.println("Document already exists: " + filename);
        }

    } finally {
        post.releaseConnection();
    }
}
 
源代码6 项目: cxf   文件: JAXRSMultipartTest.java
@Test
public void testMultipartRequestTooLarge() throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("http://localhost:" + PORT + "/bookstore/books/image");
    String ct = "multipart/mixed";
    post.setHeader("Content-Type", ct);

    HttpEntity entity = MultipartEntityBuilder.create()
        .addPart("image", new ByteArrayBody(new byte[1024 * 11], "testfile.png"))
        .build();

    post.setEntity(entity);

    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(413, response.getStatusLine().getStatusCode());
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
源代码7 项目: cxf   文件: JAXRSMultipartTest.java
@Test
public void testMultipartRequestTooLargeManyParts() throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("http://localhost:" + PORT + "/bookstore/books/image");
    String ct = "multipart/mixed";
    post.setHeader("Content-Type", ct);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    HttpEntity entity = builder.addPart("image", new ByteArrayBody(new byte[1024 * 9], "testfile.png"))
                               .addPart("image", new ByteArrayBody(new byte[1024 * 11], "testfile2.png")).build();

    post.setEntity(entity);

    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(413, response.getStatusLine().getStatusCode());
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
源代码8 项目: estatio   文件: GotenbergClientService.java
@Programmatic
public byte[] convertToPdf(
        final byte[] docxBytes,
        final String url) {

    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        final HttpPost httpPost = new HttpPost(url);

        ContentBody bin = new ByteArrayBody(docxBytes, "dummy.docx");

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("files", bin)
                .build();

        httpPost.setEntity(reqEntity);

        try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
            HttpEntity resEntity = response.getEntity();
            return resEntity != null ? EntityUtils.toByteArray(resEntity) : null;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
源代码9 项目: TrackRay   文件: HttpClient.java
/**
 * 上传文件(包括图片)
 *
 * @param url
 *            请求URL
 * @param paramsMap
 *            参数和值
 * @return
 */
public ResponseStatus post(String url, Map<String, Object> paramsMap) {
    HttpClientWrapper hw = new HttpClientWrapper(proxy);
    ResponseStatus ret = null;
    try {
        setParams(url, hw);
        Iterator<String> iterator = paramsMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Object value = paramsMap.get(key);
            if (value instanceof File) {
                FileBody fileBody = new FileBody((File) value);
                hw.getContentBodies().add(fileBody);
            } else if (value instanceof byte[]) {
                byte[] byteVlue = (byte[]) value;
                ByteArrayBody byteArrayBody = new ByteArrayBody(byteVlue, key);
                hw.getContentBodies().add(byteArrayBody);
            } else {
                if (value != null && !"".equals(value)) {
                    hw.addNV(key, String.valueOf(value));
                } else {
                    hw.addNV(key, "");
                }
            }
        }
        ret = hw.postEntity(url);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ret;
}
 
源代码10 项目: timer   文件: FileSession.java
public Session uploadFile(byte [] bytes,String filename,String appName,String dirName){
    MultipartEntityBuilder multipartEntity= (MultipartEntityBuilder) this.getProviderService().provider();
    ContentBody byteArrayBody = new ByteArrayBody(bytes, filename);
    multipartEntity.addPart("file", byteArrayBody);
    multipartEntity.addTextBody("dirName", dirName);
    multipartEntity.addTextBody("filename", filename);
    multipartEntity.addTextBody("appName",appName);
    return this;
}
 
public AwsProxyRequestBuilder formFilePart(String fieldName, String fileName, byte[] content) throws IOException {
    if (multipartBuilder == null) {
        multipartBuilder = MultipartEntityBuilder.create();
    }
    multipartBuilder.addPart(fieldName, new ByteArrayBody(content, fileName));
    buildMultipartBody();
    return this;
}
 
源代码12 项目: 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;
}
 
源代码13 项目: 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;
}
 
源代码14 项目: 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();
}
 
源代码15 项目: 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;
    }
}
 
源代码16 项目: Knowage-Server   文件: SimpleRestClient.java
@SuppressWarnings({ "rawtypes" })
private HttpResponse executeServiceMultipart(Map<String, Object> parameters, byte[] form, String serviceUrl, String userId) throws Exception {
	logger.debug("IN");
	CloseableHttpClient client = null;
	MultivaluedMap<String, Object> myHeaders = new MultivaluedHashMap<String, Object>();

	if (!serviceUrl.contains("http") && addServerUrl) {
		logger.debug("Adding the server URL");
		if (serverUrl != null) {
			logger.debug("Executing the dataset from the core so use relative path to service");
			serviceUrl = serverUrl + serviceUrl;
		}
		logger.debug("Call service URL " + serviceUrl);
	}

	try {

		if (parameters != null) {
			logger.debug("adding parameters in the request");
			StringBuilder sb = new StringBuilder(serviceUrl);
			sb.append("?");
			for (Iterator iterator = parameters.keySet().iterator(); iterator.hasNext();) {
				String key = (String) iterator.next();
				sb.append(key);
				sb.append("=");
				sb.append(parameters.get(key));
			}
			logger.debug("finish to add parameters in the request");
		}

		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.addPart("file", new ByteArrayBody(form, "file"));
		HttpPost request = new HttpPost(serviceUrl);
		request.setEntity(builder.build());
		client = HttpClientBuilder.create().build();

		String encodedBytes = Base64.encode(userId.getBytes("UTF-8"));
		request.addHeader("Authorization", "Direct " + encodedBytes);

		authenticationProvider.provideAuthenticationMultiPart(request, myHeaders);

		HttpResponse response1 = client.execute(request);

		if (response1.getStatusLine().getStatusCode() >= 400) {
			throw new RuntimeException("Request failed with HTTP error code : " + response1.getStatusLine().getStatusCode());
		}

		logger.debug("Rest query status " + response1.getStatusLine().getStatusCode());
		// logger.debug("Rest query status info "+response.getStatusInfo());
		logger.debug("Rest query status getReasonPhrase " + response1.getStatusLine().getReasonPhrase());
		logger.debug("OUT");
		return response1;
	} finally {
		if (client != null) {
			client.close();
		}
	}
}
 
源代码17 项目: WeixinMultiPlatform   文件: 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;
}
 
源代码18 项目: iaf   文件: MultipartEntityBuilder.java
public MultipartEntityBuilder addBinaryBody(String name, byte[] b, ContentType contentType, String filename) {
	return addPart(name, new ByteArrayBody(b, contentType, filename));
}
 
源代码19 项目: wisdom   文件: FileUploadTest.java
@Test
public void testThatFileUpdateFailedWhenTheFileExceedTheConfiguredSize() throws InterruptedException, IOException {
    // Prepare the configuration
    ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
    when(configuration.getIntegerWithDefault(eq("vertx.http.port"), anyInt())).thenReturn(0);
    when(configuration.getIntegerWithDefault(eq("vertx.https.port"), anyInt())).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.acceptBacklog", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.receiveBufferSize", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.sendBufferSize", -1)).thenReturn(-1);
    when(configuration.getLongWithDefault("http.upload.disk.threshold", DiskFileUpload.MINSIZE)).thenReturn
            (DiskFileUpload.MINSIZE);
    when(configuration.getLongWithDefault("http.upload.max", -1l)).thenReturn(10l); // 10 bytes max
    when(configuration.getStringArray("wisdom.websocket.subprotocols")).thenReturn(new String[0]);
    when(configuration.getStringArray("vertx.websocket-subprotocols")).thenReturn(new String[0]);

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            return ok();
        }
    };
    Router router = mock(Router.class);
    Route route = new RouteBuilder().route(HttpMethod.POST)
            .on("/")
            .to(controller, "index");
    when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route);

    ContentEngine contentEngine = getMockContentEngine();

    // Configure the server.
    server = new WisdomVertxServer();
    server.accessor = new ServiceAccessor(
            null,
            configuration,
            router,
            contentEngine,
            executor,
            null,
            Collections.<ExceptionMapper>emptyList()
    );
    server.configuration = configuration;
    server.vertx = vertx;
    server.start();

    VertxHttpServerTest.waitForStart(server);

    int port = server.httpPort();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost("http://localhost:" + port + "/?id=" + 1);

    ByteArrayBody body = new ByteArrayBody("this is too much...".getBytes(), "my-file.dat");
    StringBody description = new StringBody("my description", ContentType.TEXT_PLAIN);
    HttpEntity entity = MultipartEntityBuilder.create()
            .addPart("upload", body)
            .addPart("comment", description)
            .build();

    post.setEntity(entity);

    CloseableHttpResponse response = httpclient.execute(post);
    // We should receive a Payload too large response (413)
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(413);

}
 
源代码20 项目: wisdom   文件: FileUploadTest.java
void doWork() throws IOException {

            final byte[] data = new byte[size];
            RANDOM.nextBytes(data);

            CloseableHttpClient httpclient = null;
            CloseableHttpResponse response = null;
            try {
                httpclient = HttpClients.createDefault();
                HttpPost post = new HttpPost("http://localhost:" + port + "/?id=" + id);

                ByteArrayBody body = new ByteArrayBody(data, "my-file.dat");
                StringBody description = new StringBody("my description", ContentType.TEXT_PLAIN);
                HttpEntity entity = MultipartEntityBuilder.create()
                        .addPart("upload", body)
                        .addPart("comment", description)
                        .build();

                post.setEntity(entity);

                response = httpclient.execute(post);
                byte[] content = EntityUtils.toByteArray(response.getEntity());

                if (!isOk(response)) {
                    System.err.println("Invalid response code for " + id + " got " + response.getStatusLine()
                            .getStatusCode() + " " + new String(content));
                    fail(id);
                    return;
                }

                if (!containsExactly(content, data)) {
                    System.err.println("Invalid content for " + id);
                    fail(id);
                    return;
                }

                success(id);

            } finally {
                IOUtils.closeQuietly(httpclient);
                IOUtils.closeQuietly(response);
            }
        }
 
 类所在包
 同包方法