Refine search
return null; GenericUrl url = new GenericUrl(uploadId); HttpRequest httpRequest = bigquery .getRequestFactory() .buildPutRequest(url, new ByteArrayContent(null, toWrite, toWriteOffset, length)); httpRequest.setParser(bigquery.getObjectParser()); long limit = destOffset + length; StringBuilder range = new StringBuilder("bytes "); range.append('*'); httpRequest.getHeaders().setContentRange(range.toString()); int code; String message; HttpResponse response = null; try { response = httpRequest.execute(); code = response.getStatusCode(); message = response.getStatusMessage();
@Test public void testNoResponseBodySet_fails() throws IOException { HttpRequest request = mockHttpServer .getHttpTransport() .createRequestFactory() .buildGetRequest(new GenericUrl(mockHttpServer.getServerUrl())); request.setContent(new ByteArrayContent("text", "test content".getBytes(UTF_8))); thrown.expect(HttpResponseException.class); thrown.expectMessage("No mock response"); request.execute(); }
/** Posts an RDF model to a Solid server. **/ public String postContent( String url, String slug, String type, Model model) throws IOException { StringWriter stringWriter = new StringWriter(); model.write(stringWriter, "TURTLE"); HttpContent content = new ByteArrayContent("text/turtle", stringWriter.toString().getBytes()); HttpRequest postRequest = factory.buildPostRequest( new GenericUrl(url), content); HttpHeaders headers = new HttpHeaders(); headers.setCookie(authCookie); headers.set("Link", "<" + type + ">; rel=\"type\""); headers.set("Slug", slug); postRequest.setHeaders(headers); HttpResponse response = postRequest.execute(); validateResponse(response, 201); return response.getHeaders().getLocation(); }
@Override public JsonRPCResponse invokeAndReadResponse(JsonRPCRequest requestObject, URI endpointUri, boolean sslVerificationDisabled) throws SteemCommunicationException { try { NetHttpTransport.Builder builder = new NetHttpTransport.Builder(); // Disable SSL verification if needed if (sslVerificationDisabled && endpointUri.getScheme().equals("https")) { builder.doNotValidateCertificate(); } String requestPayload = requestObject.toJson(); HttpRequest httpRequest = builder.build().createRequestFactory(new HttpClientRequestInitializer()) .buildPostRequest(new GenericUrl(endpointUri), ByteArrayContent.fromString("application/json", requestPayload)); LOGGER.debug("Sending {}.", requestPayload); HttpResponse httpResponse = httpRequest.execute(); int status = httpResponse.getStatusCode(); String responsePayload = httpResponse.parseAsString(); if (status >= 200 && status < 300 && responsePayload != null) { return new JsonRPCResponse(CommunicationHandler.getObjectMapper().readTree(responsePayload)); } else { throw new ClientProtocolException("Unexpected response status: " + status); } } catch (GeneralSecurityException | IOException e) { throw new SteemCommunicationException("A problem occured while processing the request.", e); } }
content = null; } else { content = new ByteArrayContent("text/plain", body.toString().getBytes()); request = factory.buildPostRequest(new GenericUrl(resourceUrl), content); request.setHeaders(headers); request.setConnectTimeout(clientConnectTimeout); request.setReadTimeout(clientRequestTimeout);
requestFactory.buildPostRequest( new GenericUrl(msgContext.getStrProp(MessageContext.TRANS_URL)), new ByteArrayContent(contentType, bos.toByteArray())); logger.debug("Setting read and connect timeout to {} millis", timeoutMillis); httpRequest.setReadTimeout(timeoutMillis); httpRequest.setConnectTimeout(timeoutMillis);
Throwable exception = null; BatchJobUploadResponse batchJobUploadResponse = null; final long contentLength = content.getLength(); constructContentRangeHeaderValue( contentLength, isLastRequest, effectiveStatus)); req.setHeaders(headers); req.setLoggingEnabled(true); }); requestFactory.buildPutRequest( new GenericUrl(effectiveStatus.getResumableUploadUri()), content); requestXml = Streams.readAll(content.getInputStream(), UTF_8); content.getInputStream().reset(); HttpResponse response = httpRequest.execute(); batchJobUploadResponse = new BatchJobUploadResponse( response,
final HttpRequest request; try { request = requestFactory.buildRequest(method.getName(), new GenericUrl(URI.create(uri)), null); } catch (IOException e) { throw Throwables.propagate(e); headers.setContentLength((long) json.length); headers.setContentType(APPLICATION_JSON_UTF8); request.setContent(new ByteArrayContent(APPLICATION_JSON_UTF8, json)); } else { payloadSize = 0; request.setHeaders(headers); final HttpResponse response; try { response = request.execute(); } catch (IOException e) { future.fail(e);
private void performPostRequest() { Log.info("POST -> " + url); try { HttpRequest request = Instance.httpRequestFactory.buildPostRequest( new GenericUrl(url), new ByteArrayContent( "application/json", getPostBody().getBytes() ) ); request(request); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } }
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; }
String uploadPhotoContent(InputStream inputStream) throws IOException { // TODO: add filename InputStreamContent content = new InputStreamContent(null, inputStream); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); content.writeTo(outputStream); byte[] contentBytes = outputStream.toByteArray(); HttpContent httpContent = new ByteArrayContent(null, contentBytes); return makePostRequest(BASE_URL + "uploads/", Optional.of(PHOTO_UPLOAD_PARAMS), httpContent, String.class); }
private String initiateResumableUpload() throws IOException { String URI = "https://storage.googleapis.com/" + bucket + "/" + path; GenericUrl url = new GenericUrl(URI); HttpRequest req = requestFactory.buildPostRequest(url, new ByteArrayContent("text/plain", new byte[0])); HttpHeaders headers = new HttpHeaders(); headers.set("x-goog-resumable", "start"); headers.setContentLength((long) 0); headers.setContentType("text/plain"); req.setHeaders(headers); req.setReadTimeout((int) DEFAULT_TIMEOUT); req.setResponseHeaders(headers); HttpResponse resp; try { resp = req.execute(); } catch (IOException e) { throw e; } if (resp.getStatusCode() == 201) { String location = resp.getHeaders().getLocation(); return location; } else { throw new IOException(); } }
.httpMethod(SdkHttpMethod.fromValue(request.getRequestMethod())) .endpoint(URI.create(signRequest.getHost())) .resourcePath(SdkHttpUtils.urlEncode(signRequest.getPath(), true)) .header(ParameterConstant.X_JDCLOUD_NONCE, nonceId) .header(ParameterConstant.CONTENT_TYPE, request.getHeaders().getContentType()) .content(request.getContent() == null ? null : ((ByteArrayContent) request.getContent()).getInputStream()); if (request.getUrl() != null && request.getUrl().size() > 0) { for (Map.Entry<String, Object> entry : request.getUrl().entrySet()) { if (entry.getValue() instanceof List) { for (Object o : (List) entry.getValue()) {
for (String name : parameters.keySet()) { MultipartContent.Part part = new MultipartContent.Part( new ByteArrayContent(null, parameters.get(name).getBytes())); part.setHeaders(new HttpHeaders().set( "Content-Disposition", String.format("form-data; name=\"%s\"", name))); HttpResponse response = httpRequestFactory.buildPostRequest( SubmitUrl, content).execute(); System.out.println(IOUtils.toString(response.getContent()));
public static <R extends JdcloudRequest> ByteArrayContent formatRequestBody(String contentType, R request, String method) throws JAXBException, IOException { ByteArrayContent bodyContent = null; Object body = content(request, method); if (body == null) { return bodyContent; } if (ContentType.TEXT_XML.toString().equals(contentType)) { bodyContent = new ByteArrayContent(contentType, beanToXmlByte(body)); } else { String content = GSON.toJson(body); bodyContent = ByteArrayContent.fromString(contentType, content); } InputStream inputStream = bodyContent.getInputStream(); ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { result.write(buffer, 0, length); } return bodyContent; }
/** * 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)); }
AbstractInputStreamContent content; if (mediaContent.contentString != null) { content = ByteArrayContent.fromString(mediaContent.contentType, mediaContent.contentString); } else { content =
@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); } }
/** * Tests behavior when URL validation is enabled and the URL of the request does not match the * server's URL. */ @Test public void testUrlMismatch_fails() throws IOException { HttpRequest request = mockHttpServer .getHttpTransport() .createRequestFactory() .buildGetRequest( new GenericUrl("http://www.example.com/does_not_match_mock_http_server_url")); request.setContent(new ByteArrayContent("text", "test content".getBytes(UTF_8))); mockHttpServer.setMockResponse(new MockResponse("test response")); thrown.expect(ConnectException.class); request.execute(); }
/** * Use the REST API to "like" an object * * @param requestFactory * @param homeNetwork * @param objectId * @throws IOException */ public void like(String objectId) throws IOException { GenericUrl likeUrl = new GenericUrl(getAlfrescoAPIUrl() + getHomeNetwork() + NODES_URL + objectId + "/ratings"); HttpContent body = new ByteArrayContent("application/json", "{\"id\": \"likes\", \"myRating\": true}".getBytes()); HttpRequest request = getRequestFactory().buildPostRequest(likeUrl, body); request.execute(); System.out.println("You liked: " + objectId); }