试试这个,应该可以:
public String predict() 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 = "projectId";
// You should have already deployed a model and a version.
// For reference, see https://cloud.google.com/ml-engine/docs/deploying-models.
String modelId = "modelId";
String versionId = "versionId";
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);
try {
String contentType = "application/json";
File requestBodyFile = new File(OnlinePredictionSample.class.getClassLoader().getResource("input.txt").getFile());
HttpContent content = new FileContent(contentType, requestBodyFile);
System.out.println(content.getLength());
GoogleCredential credential = GoogleCredential.fromStream(OnlinePredictionSample.class.getClassLoader().
getResourceAsStream("client_secret.json"))
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
HttpRequest request = requestFactory.buildRequest(method.getHttpMethod(), url, content);
String response = new Gson().toJson(request.execute().parseAsString());
log.info(response);
return response;
} catch (Exception e) {
log.log(Level.SEVERE, "Cannot Make Rest to ML Google Platform ", e);
}
return null;
}