protected <E> E postRequest(String path, Object body, Class<E> responseType){ try { URI uri = uri(path); GenericUrl url = new GenericUrl(uri); if ( logger.isDebugEnabled() ){ logger.debug("Request POSTed into botframework api " + uri + ":"); logger.debug(JSON_FACTORY.toPrettyString(body)); } HttpContent content = new JsonHttpContent(JSON_FACTORY,body); HttpRequest request = requestFactory.buildPostRequest(url,content); E response = (E) request.execute().parseAs(responseType); if ( logger.isDebugEnabled() ){ logger.debug("Response back from botframework api:"); logger.debug(JSON_FACTORY.toPrettyString(response)); } return response; } catch (IOException e) { throw new RuntimeException(e); } }
protected Future<HttpResponse> postRequestAsync(String path, Object body){ try { URI uri = uri(path); GenericUrl url = new GenericUrl(); if ( logger.isDebugEnabled() ){ logger.debug("Request POSTed into botframework api " + uri + ":"); logger.debug(JSON_FACTORY.toPrettyString(body)); } HttpContent content = new JsonHttpContent(JSON_FACTORY,body); HttpRequest request = requestFactory.buildPostRequest(url,content); if ( this.executor != null ){ return request.executeAsync(this.executor); } else{ return request.executeAsync(); } } catch (IOException e) { throw new RuntimeException(e); } }
public boolean create(String name, String rules) throws VaultException { Map<String, Object> data = new HashMap<>(); data.put("rules", rules); HttpContent content = new JsonHttpContent(getJsonFactory(), data); try { HttpRequest request = getRequestFactory().buildRequest( "POST", new GenericUrl(getConf().getAddress() + "/v1/sys/policy/" + name), content ); HttpResponse response = request.execute(); if (!response.isSuccessStatusCode()) { LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage()); } return response.isSuccessStatusCode(); } catch (IOException e) { LOG.error(e.toString(), e); throw new VaultException("Failed to authenticate: " + e.toString(), e); } }
protected Secret getSecret(String path, String method, HttpContent content) throws VaultException { try { HttpRequest request = getRequestFactory().buildRequest( method, new GenericUrl(getConf().getAddress() + path), content ); HttpResponse response = request.execute(); if (!response.isSuccessStatusCode()) { LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage()); } return response.parseAs(Secret.class); } catch (IOException e) { LOG.error(e.toString(), e); throw new VaultException("Failed to authenticate: " + e.toString(), e); } }
public void putDroplets(String userName, List<Droplet> droplets) throws Exception { try { System.out.println("Perform droplet search ...."); HttpRequestFactory httpRequestFactory = createRequestFactory(transport); HttpContent content = new JsonHttpContent(new JacksonFactory(), droplets); HttpRequest request = httpRequestFactory.buildPostRequest( new GenericUrl(DROPLET_POST_URL + userName), content); HttpResponse response = request.execute(); System.out.println(response.getStatusCode()); } catch (HttpResponseException e) { System.err.println(e.getStatusMessage()); throw e; } }
public static void loggingRequest(HttpRequest request) { if ( LOGGER.isDebugEnabled()) { HttpContent httpContent = request.getContent(); String content = ""; if (httpContent != null){ ByteArrayOutputStream output = new ByteArrayOutputStream(); try { request.getContent().writeTo(output); content = output.toString(); } catch (IOException ex) { LOGGER.warn("Error io during get content request " + ex.getMessage()); content = ex.getMessage(); } } LOGGER.debug("[GloboDNSAPI request] " + request.getRequestMethod() + " URL:" + request.getUrl() + " Content:" + content); } }
/** * <pre> * status[drink_id]=50fb3d16ce007c40fc00080d&status[dealer_id]=52cd8b5e7a58b40eae004e40&status[status]=1 * </pre> */ @Override public DrinkStatus loadDataFromNetwork() throws Exception { Map<String, String> tempParameters = new HashMap<>(); tempParameters.put("status[drink_id]", drinkId); tempParameters.put("status[dealer_id]",dealerId); tempParameters.put("status[status]",drinkStatus.getStatusId()); HttpContent tempContent = new UrlEncodedContent(tempParameters); HttpRequest request = getHttpRequestFactory().buildPostRequest(new GenericUrl(URL_BASE + URL_STATUS_UPDATE), tempContent); GsonBuilder tmpBuilder = new GsonBuilder(); tmpBuilder.registerTypeAdapter(Dealer.class, new DealerDetailsDeserializer()); Gson tempGson = tmpBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); DrinkStatus tmpDealer; try (InputStream in = request.execute().getContent()) { tmpDealer = tempGson.fromJson(new InputStreamReader(in), DrinkStatus.class); if (tmpDealer == null) { Log.e(LOGTAG, "No dealer details downloaded"); } else { Log.i(LOGTAG, "Downloaded dealer details: " + tmpDealer); } } return tmpDealer; }
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); }
@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()); }
private String extractPayload(HttpHeaders headers, @Nullable HttpContent content) { StringBuilder messageBuilder = new StringBuilder(); if (headers != null) { appendMapAsString(messageBuilder, headers); } if (content != null) { messageBuilder.append(String.format("%nContent:%n")); if (content instanceof UrlEncodedContent) { UrlEncodedContent encodedContent = (UrlEncodedContent) content; appendMapAsString(messageBuilder, Data.mapOf(encodedContent.getData())); } else if (content != null) { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); try { content.writeTo(byteStream); messageBuilder.append(byteStream.toString(StandardCharsets.UTF_8.name())); } catch (IOException e) { messageBuilder.append("Unable to read request content due to exception: " + e); } } } return messageBuilder.toString(); }
private byte[] serializeContent(HttpRequest request) { byte[] contentBytes; try { HttpContent content = request.getContent(); if (content == null) { return new byte[]{}; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); content.writeTo(bos); contentBytes = bos.toByteArray(); // for non-retryable content, reset the content for downstream handlers if (!content.retrySupported()) { HttpContent newContent = new ByteArrayContent(content.getType(), contentBytes); request.setContent(newContent); } return contentBytes; } catch (IOException e) { throw new RuntimeException(e); } }
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(); }
/** * Creates a new row in Google Fusion Tables representing the track as a line * segment. * * @param fusiontables fusion tables * @param tableId the table id * @param track the track */ private void createNewLineString(Fusiontables fusiontables, String tableId, Track track) throws IOException { String values = SendFusionTablesUtils.formatSqlValues(track.getName(), track.getDescription(), SendFusionTablesUtils.getKmlLineString(track.getLocations())); String sql = "INSERT INTO " + tableId + " (name,description,geometry) VALUES " + values; HttpContent content = ByteArrayContent.fromString(null, "sql=" + sql); GoogleUrl url = new GoogleUrl("https://www.googleapis.com/fusiontables/v1/query"); fusiontables.getRequestFactory().buildPostRequest(url, content).execute(); }
<T> T postAndParse(GenericUrl url, HttpContent content, Class<T> cls) { try { HttpRequest request = this.requestFactory.buildPostRequest(url, content); return executeAndParse(request, cls); } catch (IOException ex) { throw new ConnectException("Exception encountered while calling salesforce", ex); } }
@Override public AuthenticationResponse authenticate() { HttpContent formContent = buildAuthContent(); this.authentication = postAndParse(this.authenticateUrl, formContent, AuthenticationResponse.class); if (null == this.config.instance || this.config.instance.isEmpty()) { this.baseUrl = new GenericUrl(this.authentication.instance_url()); } else { this.baseUrl = new GenericUrl(this.config.instance); } return this.authentication; }
public static void main(String[] args) throws Exception { HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); Discovery discovery = new Discovery.Builder(httpTransport, jsonFactory, null).build(); RestDescription api = discovery.apis().getRest("ml", "v1").execute(); RestMethod method = api.getResources().get("projects").getMethods().get("predict"); JsonSchema param = new JsonSchema(); String projectId = "YOUR_PROJECT_ID"; // You should have already deployed a model and a version. // For reference, see https://cloud.google.com/ml-engine/docs/deploying-models. String modelId = "YOUR_MODEL_ID"; String versionId = "YOUR_VERSION_ID"; param.set( "name", String.format("projects/%s/models/%s/versions/%s", projectId, modelId, versionId)); GenericUrl url = new GenericUrl(UriTemplate.expand(api.getBaseUrl() + method.getPath(), param, true)); System.out.println(url); String contentType = "application/json"; File requestBodyFile = new File("input.txt"); HttpContent content = new FileContent(contentType, requestBodyFile); System.out.println(content.getLength()); GoogleCredential credential = GoogleCredential.getApplicationDefault(); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential); HttpRequest request = requestFactory.buildRequest(method.getHttpMethod(), url, content); String response = request.execute().parseAsString(); System.out.println(response); }
public Secret write(String path, Map<String, Object> params) throws VaultException { HttpContent content = new JsonHttpContent( getJsonFactory(), params ); return getSecret("/v1/" + path, "POST", content); }
public boolean enable(String path, String type, String description) throws VaultException { Map<String, Object> data = new HashMap<>(); data.put("type", type); if (description != null) { data.put("description", description); } HttpContent content = new JsonHttpContent(getJsonFactory(), data); try { HttpRequest request = getRequestFactory().buildRequest( "POST", new GenericUrl(getConf().getAddress() + "/v1/sys/auth/" + path), content ); HttpResponse response = request.execute(); if (!response.isSuccessStatusCode()) { LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage()); } return response.isSuccessStatusCode(); } catch (IOException e) { LOG.error(e.toString(), e); throw new VaultException("Failed to authenticate: " + e.toString(), e); } }
public boolean mount(String path, String type, String description, Map<String, String> config) throws VaultException { Map<String, Object> data = new HashMap<>(); data.put("type", type); if (description != null) { data.put("description", description); } if (config != null) { data.put("config", config); } HttpContent content = new JsonHttpContent(getJsonFactory(), data); try { HttpRequest request = getRequestFactory().buildRequest( "POST", new GenericUrl(getConf().getAddress() + "/v1/sys/mounts/" + path), content ); HttpResponse response = request.execute(); if (!response.isSuccessStatusCode()) { LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage()); } return response.isSuccessStatusCode(); } catch (IOException e) { LOG.error(e.toString(), e); throw new VaultException("Failed to authenticate: " + e.toString(), e); } }
public Secret appRole(String roleId, String secretId) throws VaultException { HttpContent content = new JsonHttpContent( getJsonFactory(), ImmutableMap.of("role_id", roleId, "secret_id", secretId) ); return getSecret("/v1/auth/approle/login", "POST", content); }
/** * This method sends a POST request with empty content to get the unique * upload URL. * * @param initiationRequestUrl * The request URL where the initiation request will be sent */ private HttpResponse executeUploadInitiation(GenericUrl initiationRequestUrl) throws IOException { updateStateAndNotifyListener(UploadState.INITIATION_STARTED); initiationRequestUrl.put("uploadType", "resumable"); HttpContent content = metadata == null ? new EmptyContent() : metadata; HttpRequest request = requestFactory.buildRequest( initiationRequestMethod, initiationRequestUrl, content); initiationHeaders.set(CONTENT_TYPE_HEADER, mediaContent.getType()); if (isMediaLengthKnown()) { initiationHeaders.set(CONTENT_LENGTH_HEADER, getMediaContentLength()); } request.getHeaders().putAll(initiationHeaders); HttpResponse response = executeCurrentRequest(request); boolean notificationCompleted = false; try { updateStateAndNotifyListener(UploadState.INITIATION_COMPLETE); notificationCompleted = true; } finally { if (!notificationCompleted) { response.disconnect(); } } return response; }
/** * Do a POST Request, creating a new user if necessary * * @param endpoint Kickflip endpoint. e.g /user/new * @param body POST body * @param responseClass Class of the expected response * @param cb Callback that will receive an instance of responseClass */ private void post(final String endpoint, final HttpContent body, final Class responseClass, final KickflipCallback cb) { acquireAccessToken(new OAuthCallback() { @Override public void onSuccess(HttpRequestFactory requestFactory) { request(requestFactory, METHOD.POST, makeApiUrl(endpoint), body, responseClass, cb); } @Override public void onFailure(Exception e) { postExceptionToCallback(cb, UNKNOWN_ERROR_CODE); } }); }
HTTPRequestInfo(HttpRequest req) { method = req.getRequestMethod(); url = req.getUrl().toURL(); long myLength; HttpContent content = req.getContent(); try { myLength = content == null ? -1 : content.getLength(); } catch (IOException e) { myLength = -1; } length = myLength; h1 = req.getHeaders(); h2 = null; }
/** * Generate a meme. * * @param topText the text to appear on the top of the image * @param bottomText the text to appear on the bottom of the image * @return meme URL */ private Optional<String> generateMeme(String templateId, String topText, String bottomText) { logger.info("Generating meme: \"{}\" \"{}\" \"{}\"", templateId, topText, bottomText); GenericUrl url; try { url = new GenericUrl(BASE_URL + IMAGE_URL); HttpContent content = new UrlEncodedContent( new CaptionRequest(templateId, username, password, topText, bottomText)); HttpRequest request = requestFactory.buildPostRequest(url, content); HttpResponse response = request.execute(); CaptionResponse captionResponse = response.parseAs(CaptionResponse.class); if (captionResponse.success) { return Optional.of(captionResponse.data.url); } else { logger.error("Error making API query: {}", captionResponse.error_message); return Optional.empty(); } } catch (IOException e) { logger.error("Error making API query: {}", e); } return Optional.empty(); }
private String getStringFromPOST(String scheme, String host, String path, String query, String key) { String rm = null; try { HttpTransport httpTransport = new NetHttpTransport(); HttpRequestFactory httpRequestFactory = httpTransport .createRequestFactory(); String data = "query=" + query + "&key=" + key; HttpContent content = new ByteArrayContent( "application/x-www-form-urlencoded", data.getBytes()); GenericUrl url = new GenericUrl( "https://www.googleapis.com/freebase/v1/mqlread"); HttpRequest request = httpRequestFactory.buildPostRequest(url, content); HttpHeaders headers = new HttpHeaders(); headers.put("X-HTTP-Method-Override", "GET"); request.setHeaders(headers); com.google.api.client.http.HttpResponse response = request .execute(); InputStream is = response.getContent(); if (is != null) { String s = convertinputStreamToString(is); rm = s; return rm; } } catch (IOException e) { e.printStackTrace(); } return rm; }
@Test public void testWrongPath() throws IOException { JsonObject request = new JsonObject(); request.addProperty("method", "TimeService.GetTime"); request.addProperty("id", "identifier"); JsonObject parameter = new JsonObject(); parameter.addProperty("timezone", DateTimeZone.UTC.getID()); JsonArray parameters = new JsonArray(); parameters.add(parameter); request.add("params", parameters); HttpContent httpContent = new ByteArrayContent("application/json", new Gson().toJson(request).getBytes(Charsets.UTF_8)); 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(404, response.error().status().code()); }
@Test public void testWrongHttpMethod() throws IOException { JsonObject request = new JsonObject(); request.addProperty("method", "TimeService.GetTime"); request.addProperty("id", "identifier"); JsonObject parameter = new JsonObject(); parameter.addProperty("timezone", DateTimeZone.UTC.getID()); JsonArray parameters = new JsonArray(); parameters.add(parameter); request.add("params", parameters); HttpContent httpContent = new ByteArrayContent("application/json", new Gson().toJson(request).getBytes(Charsets.UTF_8)); GenericUrl url = new GenericUrl(); url.setScheme("http"); url.setHost("localhost"); url.setPort(port); url.setRawPath("/rpc"); HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory(); HttpRequest httpRequest = requestFactory.buildPutRequest(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(405, response.error().status().code()); }
@Test public void testMissingService() throws IOException { JsonObject request = new JsonObject(); request.addProperty("method", ".GetTime"); request.addProperty("id", "identifier"); JsonObject parameter = new JsonObject(); parameter.addProperty("timezone", DateTimeZone.UTC.getID()); JsonArray parameters = new JsonArray(); parameters.add(parameter); request.add("params", parameters); HttpContent httpContent = new ByteArrayContent("application/json", new Gson().toJson(request).getBytes(Charsets.UTF_8)); GenericUrl url = new GenericUrl(); url.setScheme("http"); url.setHost("localhost"); url.setPort(port); url.setRawPath("/rpc"); 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()); }
@Test public void testMissingMethod() throws IOException { JsonObject request = new JsonObject(); request.addProperty("method", "TimeService."); request.addProperty("id", "identifier"); JsonObject parameter = new JsonObject(); parameter.addProperty("timezone", DateTimeZone.UTC.getID()); JsonArray parameters = new JsonArray(); parameters.add(parameter); request.add("params", parameters); HttpContent httpContent = new ByteArrayContent("application/json", new Gson().toJson(request).getBytes(Charsets.UTF_8)); GenericUrl url = new GenericUrl(); url.setScheme("http"); url.setHost("localhost"); url.setPort(port); url.setRawPath("/rpc"); 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()); }
@Test public void testMissingId() throws IOException { JsonObject request = new JsonObject(); request.addProperty("method", "TimeService.GetTime"); JsonObject parameter = new JsonObject(); parameter.addProperty("timezone", DateTimeZone.UTC.getID()); JsonArray parameters = new JsonArray(); parameters.add(parameter); request.add("params", parameters); HttpContent httpContent = new ByteArrayContent("application/json", new Gson().toJson(request).getBytes(Charsets.UTF_8)); GenericUrl url = new GenericUrl(); url.setScheme("http"); url.setHost("localhost"); url.setPort(port); url.setRawPath("/rpc"); 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()); }
@Test public void testMissingParam() throws IOException { JsonObject request = new JsonObject(); request.addProperty("method", ".GetTime"); request.addProperty("id", "identifier"); JsonObject parameter = new JsonObject(); parameter.addProperty("timezone", DateTimeZone.UTC.getID()); HttpContent httpContent = new ByteArrayContent("application/json", new Gson().toJson(request).getBytes(Charsets.UTF_8)); GenericUrl url = new GenericUrl(); url.setScheme("http"); url.setHost("localhost"); url.setPort(port); url.setRawPath("/rpc"); 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()); }
@Override public HttpContent getHttpContent() { Map<String, String> data = Maps.newHashMap(); data.put(REPORT_QUERY_KEY, reportQuery); data.put(FORMAT_KEY, format); return new UrlEncodedContent(data); }
public HttpRequest buildRequest(String method, GenericUrl url, HttpContent content) throws IOException { if (app.credential == null) { throw new IOException("OAuthDispatcher: access token not set"); } return httpTransport.createRequestFactory(app.credential).buildRequest(method, url, content); }
public HttpRequest buildRequest(String method, GenericUrl url, HttpContent content) throws IOException { HttpRequest request = super.buildRequest(method, url, content); request.getHeaders().setAuthorization("Bearer " + accessToken); return request; }
public HttpRequest buildRequest(String method, GenericUrl url, HttpContent content) throws IOException { HttpRequest request = super.buildRequest(method, url, content); request.getHeaders().setBasicAuthentication(this.apiKey, ""); return request; }
public HttpRequest buildRequest(String method, GenericUrl url, HttpContent content) throws IOException { return httpTransport.createRequestFactory().buildRequest(method, url, content); }
public EventsRequest<T> data(HttpContent content) { return (EventsRequest<T>) super.data(content); }
public ItemRequest<T> data(HttpContent content) { return (ItemRequest<T>) super.data(content); }
public CollectionRequest<T> data(HttpContent content) { return (CollectionRequest<T>) super.data(content); }