如何使用Google ml API修复无效范围(400错误的请求)

我尝试使用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"
}

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

super_grubby 回答:如何使用Google ml API修复无效范围(400错误的请求)

这是我找到的解决方案:

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

本文链接:https://www.f2er.com/3118647.html

大家都在问