Java 类com.google.api.client.http.UriTemplate 实例源码

项目:java-docs-samples    文件:OnlinePredictionSample.java   
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);
}