本文整理汇总了Java中com.google.api.client.http.ByteArrayContent类的典型用法代码示例。如果您正苦于以下问题:Java ByteArrayContent类的具体用法?Java ByteArrayContent怎么用?Java ByteArrayContent使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ByteArrayContent类属于com.google.api.client.http包,在下文中一共展示了ByteArrayContent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: uploadFile
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
@Override
public void uploadFile(String path, byte[] data, boolean writeTransactional)
throws Exception {
logDebug("upload file...");
try
{
ByteArrayContent content = new ByteArrayContent(null, data);
GDrivePath gdrivePath = new GDrivePath(path);
Drive driveService = getDriveService(gdrivePath.getAccount());
File driveFile = getFileForPath(gdrivePath, driveService);
getDriveService(gdrivePath.getAccount()).files()
.update(driveFile.getId(), driveFile, content).execute();
logDebug("upload file ok.");
}
catch (Exception e)
{
throw convertException(e);
}
}
示例2: sendPostMultipart
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
public static int sendPostMultipart(String urlString, Map<String, String> parameters)
throws IOException {
MultipartContent postBody = new MultipartContent()
.setMediaType(new HttpMediaType("multipart/form-data"));
postBody.setBoundary(MULTIPART_BOUNDARY);
for (Map.Entry<String, String> entry : parameters.entrySet()) {
HttpContent partContent = ByteArrayContent.fromString( // uses UTF-8 internally
null /* part Content-Type */, entry.getValue());
HttpHeaders partHeaders = new HttpHeaders()
.set("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\"");
postBody.addPart(new MultipartContent.Part(partHeaders, partContent));
}
GenericUrl url = new GenericUrl(new URL(urlString));
HttpRequest request = transport.createRequestFactory().buildPostRequest(url, postBody);
request.setHeaders(new HttpHeaders().setUserAgent(CloudToolsInfo.USER_AGENT));
request.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MS);
request.setReadTimeout(DEFAULT_READ_TIMEOUT_MS);
HttpResponse response = request.execute();
return response.getStatusCode();
}
示例3: graphql
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
private JsonObject graphql(String query)
throws IOException
{
String payload = Json.createObjectBuilder()
.add("query", query)
.add("variables", "{}")
.build().toString();
HttpRequest request = requestFactory.buildPostRequest(
new GenericUrl(GRAPHQL_ENDPOINT),
ByteArrayContent.fromString("application/json", payload));
HttpHeaders headers = new HttpHeaders();
headers.setAuthorization("bearer " + tokenFactory.getToken());
request.setHeaders(headers);
HttpResponse response = executeWithRetry(request);
// TODO: Handle error status code
JsonObject responseObject = Json.createReader(new StringReader(response.parseAsString())).readObject();
if (responseObject.containsKey("errors")) {
LOG.debug("errors with query:\n" + query);
LOG.debug("response:\n" + responseObject.toString());
}
return responseObject;
}
示例4: prepareEmptyInsert
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
/**
* Helper for creating a Storage.Objects.Copy object ready for dispatch given a bucket and
* object for an empty object to be created. Caller must already verify that {@code resourceId}
* represents a StorageObject and not a bucket.
*/
private Storage.Objects.Insert prepareEmptyInsert(StorageResourceId resourceId,
CreateObjectOptions createObjectOptions) throws IOException {
StorageObject object = new StorageObject();
object.setName(resourceId.getObjectName());
Map<String, String> rewrittenMetadata = encodeMetadata(createObjectOptions.getMetadata());
object.setMetadata(rewrittenMetadata);
// Ideally we'd use EmptyContent, but Storage requires an AbstractInputStreamContent and not
// just an HttpContent, so we'll just use the next easiest thing.
ByteArrayContent emptyContent =
new ByteArrayContent(createObjectOptions.getContentType(), new byte[0]);
Storage.Objects.Insert insertObject = gcs.objects().insert(
resourceId.getBucketName(), object, emptyContent);
insertObject.setDisableGZipContent(true);
clientRequestHelper.setDirectUploadEnabled(insertObject, true);
if (resourceId.hasGenerationId()) {
insertObject.setIfGenerationMatch(resourceId.getGenerationId());
} else if (!createObjectOptions.overwriteExisting()) {
insertObject.setIfGenerationMatch(0L);
}
return insertObject;
}
示例5: upload
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
/**
* Upload a wordMLPackage (or presentationML or spreadsheetML pkg) to Google
* Drive as a docx
*
* @param service
* @param wordMLPackage
* @param title
* @param description
* @param shareReadableWithEveryone
* @throws IOException
* @throws Docx4JException
*/
public static void upload(Drive service, OpcPackage wordMLPackage,
String title, String description, boolean shareReadableWithEveryone)
throws IOException, Docx4JException {
// Insert a file
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(DOCX_MIME);
ByteArrayContent mediaContent = new ByteArrayContent(DOCX_MIME,
getDocxAsByteArray(wordMLPackage));
File file = service.files().insert(body, mediaContent).execute();
System.out.println("File ID: " + file.getId());
// https://developers.google.com/drive/v2/reference/permissions/insert
if (shareReadableWithEveryone) {
insertPermission(service, file.getId(), null, "anyone", "reader");
System.out.println(".. shared");
}
}
示例6: uploadTestFile
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
private static File uploadTestFile(ProducerTemplate template, String testName) {
File fileMetadata = new File();
fileMetadata.setTitle(GoogleDriveIntegrationTest.class.getName()+"."+testName+"-"+ UUID.randomUUID().toString());
final String content = "Camel rocks!\n" //
+ DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()) + "\n" //
+ "user: " + System.getProperty("user.name");
HttpContent mediaContent = new ByteArrayContent("text/plain", content.getBytes(StandardCharsets.UTF_8));
final Map<String, Object> headers = new HashMap<>();
// parameter type is com.google.api.services.drive.model.File
headers.put("CamelGoogleDrive.content", fileMetadata);
// parameter type is com.google.api.client.http.AbstractInputStreamContent
headers.put("CamelGoogleDrive.mediaContent", mediaContent);
return template.requestBodyAndHeaders("google-drive://drive-files/insert", null, headers, File.class);
}
示例7: createShopResource
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
public String createShopResource(String targetResource, List<Parameter> parameters, String resourcePayload)
throws ShopifyException {
try {
GenericUrl url = processParameters(targetResource, parameters);
// HttpContent
//
ByteArrayContent contentBytes = new ByteArrayContent(null, resourcePayload.getBytes());
// Post Request
//
HttpRequest request = _requestFactory.buildPostRequest(url, contentBytes);
request.getHeaders().setContentType("application/json");
request.getHeaders().setAuthorization("Basic " + encodedAuthentication);
System.out.println(request.getUrl().toString());
HttpResponse response = request.execute();
return response.parseAsString();
} catch (Exception ex) {
throw new ShopifyException(ex);
}
}
示例8: updateShopResource
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
public String updateShopResource(String targetResource, List<Parameter> parameters, String resourcePayload)
throws ShopifyException {
try {
GenericUrl url = processParameters(targetResource, parameters);
// HttpContent
//
ByteArrayContent contentBytes = new ByteArrayContent(null, resourcePayload.getBytes());
// Put Request
//
HttpRequest request = _requestFactory.buildPutRequest(url, contentBytes);
request.getHeaders().setContentType("application/json");
request.getHeaders().setAuthorization("Basic " + encodedAuthentication);
System.out.println(request.getUrl().toString());
HttpResponse response = request.execute();
return response.parseAsString();
} catch (Exception ex) {
throw new ShopifyException(ex);
}
}
示例9: patchShopResource
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
public String patchShopResource(String targetResource, List<Parameter> parameters, String resourcePayload)
throws ShopifyException {
try {
GenericUrl url = processParameters(targetResource, parameters);
// HttpContent
//
ByteArrayContent contentBytes = new ByteArrayContent(null, resourcePayload.getBytes());
// Patch Request
//
HttpRequest request = _requestFactory.buildPatchRequest(url, contentBytes);
request.getHeaders().setContentType("application/json");
request.getHeaders().setAuthorization("Basic " + encodedAuthentication);
System.out.println(request.getUrl().toString());
HttpResponse response = request.execute();
return response.parseAsString();
} catch (Exception ex) {
throw new ShopifyException(ex);
}
}
示例10: testMissingBody
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
@Test
public void testMissingBody() throws IOException {
HttpContent httpContent = new ByteArrayContent("application/json",
new byte[]{});
GenericUrl url = new GenericUrl();
url.setScheme("http");
url.setHost("localhost");
url.setPort(port);
url.setRawPath("/tox");
HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
HttpRequest httpRequest = requestFactory.buildPostRequest(url, httpContent);
HttpResponse httpResponse = httpRequest.execute();
Assert.assertEquals(HttpStatusCodes.STATUS_CODE_OK, httpResponse.getStatusCode());
Reader reader = new InputStreamReader(httpResponse.getContent(), Charsets.UTF_8);
JsonRpcResponse response = JsonRpcResponse.fromJson(new JsonParser().parse(reader)
.getAsJsonObject());
Assert.assertTrue(response.isError());
Assert.assertEquals(400, response.error().status().code());
}
示例11: postProcessContent
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
/**
* Post-processes the request content to conform to the requirements of Google Cloud Storage.
*
* @param content the content produced by the {@link BatchJobUploadBodyProvider}.
* @param isFirstRequest if this is the first request for the batch job.
* @param isLastRequest if this is the last request for the batch job.
*/
private ByteArrayContent postProcessContent(
ByteArrayContent content, boolean isFirstRequest, boolean isLastRequest) throws IOException {
if (isFirstRequest && isLastRequest) {
return content;
}
String serializedRequest = Streams.readAll(content.getInputStream(), UTF_8);
serializedRequest = trimStartEndElements(serializedRequest, isFirstRequest, isLastRequest);
// The request is part of a set of incremental uploads, so pad to the required content
// length. This is not necessary if all operations for the job are being uploaded in a
// single request.
int numBytes = serializedRequest.getBytes(UTF_8).length;
int remainder = numBytes % REQUIRED_CONTENT_LENGTH_INCREMENT;
if (remainder > 0) {
int pad = REQUIRED_CONTENT_LENGTH_INCREMENT - remainder;
serializedRequest = Strings.padEnd(serializedRequest, numBytes + pad, ' ');
}
return new ByteArrayContent(content.getType(), serializedRequest.getBytes(UTF_8));
}
示例12: testUploadBatchJobOperations_ioException_fails
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
/**
* Tests that IOExceptions from executing an upload request are propagated properly.
*/
@SuppressWarnings("rawtypes")
@Test
public void testUploadBatchJobOperations_ioException_fails() throws Exception {
final IOException ioException = new IOException("mock IO exception");
MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest(){
@Override
public LowLevelHttpResponse execute() throws IOException {
throw ioException;
}
};
when(uploadBodyProvider.getHttpContent(request, true, true))
.thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8)));
MockHttpTransport transport = new MockHttpTransport.Builder()
.setLowLevelHttpRequest(lowLevelHttpRequest).build();
uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger);
BatchJobUploadStatus uploadStatus =
new BatchJobUploadStatus(0, URI.create("http://www.example.com"));
thrown.expect(BatchJobException.class);
thrown.expectCause(Matchers.sameInstance(ioException));
uploader.uploadIncrementalBatchJobOperations(request, true, uploadStatus);
}
示例13: testUploadBatchJobOperations_initiateFails_fails
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
/**
* Tests that IOExceptions from initiating an upload are propagated properly.
*/
@SuppressWarnings("rawtypes")
@Test
public void testUploadBatchJobOperations_initiateFails_fails() throws Exception {
final IOException ioException = new IOException("mock IO exception");
MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest(){
@Override
public LowLevelHttpResponse execute() throws IOException {
throw ioException;
}
};
when(uploadBodyProvider.getHttpContent(request, true, true))
.thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8)));
MockHttpTransport transport = new MockHttpTransport.Builder()
.setLowLevelHttpRequest(lowLevelHttpRequest).build();
uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger);
thrown.expect(BatchJobException.class);
thrown.expectCause(Matchers.sameInstance(ioException));
thrown.expectMessage("initiate upload");
uploader.uploadIncrementalBatchJobOperations(request, true, new BatchJobUploadStatus(
0, URI.create("http://www.example.com")));
}
示例14: testUploadIncrementalBatchJobOperations_logging
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
@Test
public void testUploadIncrementalBatchJobOperations_logging() throws Exception {
BatchJobUploadStatus status =
new BatchJobUploadStatus(10, URI.create(mockHttpServer.getServerUrl()));
String uploadRequestBody = "<mutate>testUpload</mutate>";
when(uploadBodyProvider.getHttpContent(request, false, true))
.thenReturn(new ByteArrayContent(null, uploadRequestBody.getBytes(UTF_8)));
mockHttpServer.setMockResponse(new MockResponse("testUploadResponse"));
String expectedBody = "testUpload</mutate>";
expectedBody =
Strings.padEnd(expectedBody, BatchJobUploader.REQUIRED_CONTENT_LENGTH_INCREMENT, ' ');
// Invoke the incremental upload method.
BatchJobUploadResponse response =
uploader.uploadIncrementalBatchJobOperations(request, true, status);
verify(batchJobLogger, times(1)).logUpload(
expectedBody,
status.getResumableUploadUri(),
response,
null
);
}
示例15: testValidOperations
import com.google.api.client.http.ByteArrayContent; //导入依赖的package包/类
@Test
public void testValidOperations() throws BatchJobException, IOException, SAXException {
RequestT request = createMutateRequest();
addBudgetOperation(request, -1L, "Test budget", 50000000L, "STANDARD");
addCampaignOperation(
request, -2L, "Test campaign #1", "PAUSED", "SEARCH", -1L, "MANUAL_CPC", false);
addCampaignOperation(
request, -3L, "Test campaign #2", "PAUSED", "SEARCH", -1L, "MANUAL_CPC", false);
addCampaignNegativeKeywordOperation(request, -2L, "venus", "BROAD");
addCampaignNegativeKeywordOperation(request, -3L, "venus", "BROAD");
ByteArrayContent httpContent =
request.createBatchJobUploadBodyProvider().getHttpContent(request, true, true);
String actualRequestXml = Streams.readAll(httpContent.getInputStream(), Charset.forName(UTF_8));
actualRequestXml =
SoapRequestXmlProvider.normalizeXmlForComparison(actualRequestXml, getApiVersion());
String expectedRequestXml = SoapRequestXmlProvider.getTestBatchUploadRequest(getApiVersion());
// Perform an XML diff using the custom difference listener that properly handles namespaces
// and attributes.
Diff diff = new Diff(expectedRequestXml, actualRequestXml);
DifferenceListener diffListener = new CustomDifferenceListener();
diff.overrideDifferenceListener(diffListener);
XMLAssert.assertXMLEqual("Serialized upload request does not match expected XML", diff, true);
}