1

我尝试使用 Java google ml api 发送预测请求。我的内容是一个 int 数组(它来自图像),我创建了一个 JsonHttpContent,但不确定它是否是执行预测请求的方式。我在本地有凭据 json 密钥。这里的请求:

  def main(args: Array[String]): Unit = {
implicit val formats = DefaultFormats

val credentials = "creds.json"
val httpTransport = GoogleNetHttpTransport.newTrustedTransport
val jsonFactory = new JacksonFactory
val discovery = new Discovery(httpTransport, jsonFactory, null)
val api = discovery.apis.getRest("ml", "v1").execute
val method = api.getResources.get("projects").getMethods.get("predict")
val param = new JsonSchema
val projectId = "ml-training"

val modelId = "my-model"
param.set("name",s"""projects/$projectId/models/$modelId""")
val url = new GenericUrl(UriTemplate.expand(api.getBaseUrl + method.getPath, param, true))
val contentType = "application/json"
val payload  = Map("instances" -> Array(255,255,255))
val content = new JsonHttpContent(jsonFactory,payload)

println(write(content))

val credential = GoogleCredential.fromStream(new FileInputStream(credentials))
val requestFactory = httpTransport.createRequestFactory(credential)
val request = requestFactory.buildRequest(method.getHttpMethod, url, content)
val response = request.execute.parseAsString
println(response)
  }

这是错误:

Exception in thread "main" com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_scope",
  "error_description" : "Bad Request"
}

我不明白我的问题的根源。是来自请求的内容吗?提前致谢

4

1 回答 1

0

这是我找到的解决方案:

val credentials = GoogleCredentials.fromStream(new FileInputStream(creds)).createScoped(
  java.util.Arrays.asList("https://www.googleapis.com/auth/cloud-platform")
)
credentials.refreshIfExpired()
val accessToken = credentials.getAccessToken

并在 http 调用的标头中使用 accessToken

于 2019-11-14T08:30:55.697 回答