當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpRequestFactory.buildPostRequest方法代碼示例

本文整理匯總了Java中com.google.api.client.http.HttpRequestFactory.buildPostRequest方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpRequestFactory.buildPostRequest方法的具體用法?Java HttpRequestFactory.buildPostRequest怎麽用?Java HttpRequestFactory.buildPostRequest使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.google.api.client.http.HttpRequestFactory的用法示例。


在下文中一共展示了HttpRequestFactory.buildPostRequest方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: PostOrderWithTokensOnly

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
/**
 * Post an order using the token and secret token to authenticate in DEAL.
 * To demonstrate successful authentication a POST request is executed.
 * 
 * @param messageToBePosted the JSON string representing the order
 * @return the result of the post action
 * 
 * @throws Exception on an exception occurring
 */
public static String PostOrderWithTokensOnly(String messageToBePosted)
		throws Exception
{
	// utilize accessToken to access protected resource in DEAL
	HttpRequestFactory factory = TRANSPORT
			.createRequestFactory(getParameters());
	GenericUrl url = new GenericUrl(PROTECTED_ORDERS_URL);
	InputStream stream = new ByteArrayInputStream(
			messageToBePosted.getBytes());
	InputStreamContent content = new InputStreamContent(JSON_IDENTIFIER,
			stream);
	HttpRequest req = factory.buildPostRequest(url, content);

	HttpResponse resp = req.execute();
	String response = resp.parseAsString();

	// log the response
	if (resp.getStatusCode() != 200 && LOG.isInfoEnabled())
	{
		LOG.info("Response Status Code: " + resp.getStatusCode());
		LOG.info("Response body:" + response);
	}

	return response;
}
 
開發者ID:krevelen,項目名稱:coala,代碼行數:35,代碼來源:DealOAuth1Util.java

示例2: post

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
@Override
public <T> T post(String path, Object request, Type responseType)
    throws RepoException, ValidationException {
  HttpRequestFactory requestFactory = getHttpRequestFactory(getCredentials());

  GenericUrl url = new GenericUrl(URI.create(API_URL + "/" + path));
  try {
    HttpRequest httpRequest = requestFactory.buildPostRequest(url,
        new JsonHttpContent(JSON_FACTORY, request));
    HttpResponse response = httpRequest.execute();
    return (T) response.parseAs(responseType);
  } catch (IOException e) {
    throw new RepoException("Error running GitHub API operation " + path, e);
  }
}
 
開發者ID:google,項目名稱:copybara,代碼行數:17,代碼來源:GitHubApiTransportImpl.java

示例3: putDroplets

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
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;
    }
}
 
開發者ID:ZanyGnu,項目名稱:GeoNote,代碼行數:19,代碼來源:DropletServer.java

示例4: testMissingBody

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的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());
}
 
開發者ID:jsilland,項目名稱:piezo,代碼行數:25,代碼來源:HttpJsonRpcServerTest.java

示例5: postRequest

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
@VisibleForTesting
InputStream postRequest(String url, String boundary, String content) throws IOException {
  HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(url),
      ByteArrayContent.fromString("multipart/form-data; boundary=" + boundary, content));
  request.setReadTimeout(60000);  // 60 seconds is the max App Engine request time
  HttpResponse response = request.execute();
  if (response.getStatusCode() >= 300) {
    throw new IOException("Client Generation failed at server side: " + response.getContent());
  } else {
    return response.getContent();
  }
}
 
開發者ID:cloudendpoints,項目名稱:endpoints-java,代碼行數:14,代碼來源:CloudClientLibGenerator.java

示例6: doPost

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
@Override
public final void doPost(final HttpServletRequest req, final HttpServletResponse resp)
    throws IOException {
  HttpTransport httpTransport;
  try {
    Map<Object, Object> params = new HashMap<>();
    params.putAll(req.getParameterMap());
    params.put("task", req.getHeader("X-AppEngine-TaskName"));

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential.getApplicationDefault()
        .createScoped(Collections.singleton("https://www.googleapis.com/auth/userinfo.email"));
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
    GenericUrl url = new GenericUrl(ConfigurationConstants.IMAGE_RESIZER_URL);

    HttpRequest request = requestFactory.buildPostRequest(url, new UrlEncodedContent(params));
    credential.initialize(request);

    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      log("Call to the imageresizer failed: " + response.getContent().toString());
      resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR);
    } else {
      resp.setStatus(response.getStatusCode());
    }

  } catch (GeneralSecurityException | IOException e) {
    log("Http request error: " + e.getMessage());
    resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR);
  }
}
 
開發者ID:googlearchive,項目名稱:abelana,代碼行數:32,代碼來源:TaskQueueNotificationServlet.java

示例7: getStringFromPOST

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
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;
}
 
開發者ID:jctoledo,項目名稱:abselexsubmitparser,代碼行數:31,代碼來源:URLReader.java

示例8: testWrongPath

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
@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());
}
 
開發者ID:jsilland,項目名稱:piezo,代碼行數:34,代碼來源:HttpJsonRpcServerTest.java

示例9: testMissingService

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
@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());
}
 
開發者ID:jsilland,項目名稱:piezo,代碼行數:34,代碼來源:HttpJsonRpcServerTest.java

示例10: testMissingMethod

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
@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());
}
 
開發者ID:jsilland,項目名稱:piezo,代碼行數:34,代碼來源:HttpJsonRpcServerTest.java

示例11: testMissingId

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
@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());
}
 
開發者ID:jsilland,項目名稱:piezo,代碼行數:33,代碼來源:HttpJsonRpcServerTest.java

示例12: testMissingParam

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
@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());
}
 
開發者ID:jsilland,項目名稱:piezo,代碼行數:31,代碼來源:HttpJsonRpcServerTest.java

示例13: initiateResumableUpload

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
/**
 * Initiates the resumable upload by sending a request to Google Cloud Storage.
 *
 * @param batchJobUploadUrl the {@code uploadUrl} of a {@code BatchJob}
 * @return the URI for the initiated resumable upload
 */
private URI initiateResumableUpload(URI batchJobUploadUrl) throws BatchJobException {
  // This follows the Google Cloud Storage guidelines for initiating resumable uploads:
  // https://cloud.google.com/storage/docs/resumable-uploads-xml
  HttpRequestFactory requestFactory =
      httpTransport.createRequestFactory(new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) throws IOException {
          HttpHeaders headers = createHttpHeaders();
          headers.setContentLength(0L);
          headers.set("x-goog-resumable", "start");
          request.setHeaders(headers);
          request.setLoggingEnabled(true);
        }
      });

  try {
    HttpRequest httpRequest =
        requestFactory.buildPostRequest(new GenericUrl(batchJobUploadUrl), new EmptyContent());
    HttpResponse response = httpRequest.execute();
    if (response.getHeaders() == null || response.getHeaders().getLocation() == null) {
      throw new BatchJobException(
          "Initiate upload failed. Resumable upload URI was not in the response.");
    }
    return URI.create(response.getHeaders().getLocation());
  } catch (IOException e) {
    throw new BatchJobException("Failed to initiate upload", e);
  }
}
 
開發者ID:googleads,項目名稱:googleads-java-lib,代碼行數:35,代碼來源:BatchJobUploader.java

示例14: labelDataset

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
/**
 * Add or modify a label on a dataset.
 *
 * <p>See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelDataset(
    String projectId, String datasetId, String labelKey, String labelValue) throws IOException {

  // Authenticate requests using Google Application Default credentials.
  GoogleCredential credential = GoogleCredential.getApplicationDefault();
  credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));

  // Get a new access token.
  // Note that access tokens have an expiration. You can reuse a token rather than requesting a
  // new one if it is not yet expired.
  credential.refreshToken();
  String accessToken = credential.getAccessToken();

  // Set the content of the request.
  Dataset dataset = new Dataset();
  dataset.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url = new GenericUrl(String.format(urlFormat, projectId, datasetId, accessToken));
  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(url, content);
  request.setParser(JSON_FACTORY.createJsonObjectParser());

  // Workaround for transports which do not support PATCH requests.
  // See: http://stackoverflow.com/a/32503192/101923
  request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
  HttpResponse response = request.execute();

  // Check for errors.
  if (response.getStatusCode() != 200) {
    throw new RuntimeException(response.getStatusMessage());
  }

  Dataset responseDataset = response.parseAs(Dataset.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseDataset.getLabels().get(labelKey));
}
 
開發者ID:GoogleCloudPlatform,項目名稱:java-docs-samples,代碼行數:49,代碼來源:LabelsSample.java

示例15: labelTable

import com.google.api.client.http.HttpRequestFactory; //導入方法依賴的package包/類
/**
 * Add or modify a label on a table.
 *
 * <p>See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelTable(
    String projectId,
    String datasetId,
    String tableId,
    String labelKey,
    String labelValue)
    throws IOException {

  // Authenticate requests using Google Application Default credentials.
  GoogleCredential credential = GoogleCredential.getApplicationDefault();
  credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));

  // Get a new access token.
  // Note that access tokens have an expiration. You can reuse a token rather than requesting a
  // new one if it is not yet expired.
  credential.refreshToken();
  String accessToken = credential.getAccessToken();

  // Set the content of the request.
  Table table = new Table();
  table.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, table);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url =
      new GenericUrl(String.format(urlFormat, projectId, datasetId, tableId, accessToken));
  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(url, content);
  request.setParser(JSON_FACTORY.createJsonObjectParser());

  // Workaround for transports which do not support PATCH requests.
  // See: http://stackoverflow.com/a/32503192/101923
  request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
  HttpResponse response = request.execute();

  // Check for errors.
  if (response.getStatusCode() != 200) {
    throw new RuntimeException(response.getStatusMessage());
  }

  Table responseTable = response.parseAs(Table.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseTable.getLabels().get(labelKey));
}
 
開發者ID:GoogleCloudPlatform,項目名稱:java-docs-samples,代碼行數:55,代碼來源:LabelsSample.java


注:本文中的com.google.api.client.http.HttpRequestFactory.buildPostRequest方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。