如何通过JsonObjectRequest向谷歌发送API请求?

问题描述 投票:0回答:1

我想在我的Android应用程序中测试云视觉API。

该API已激活,可在Google Cloud Explorer中使用,如下图所示。

Google APIs Explorer

如何通过RequestQueue对象发出简单的帖子请求?

我尝试了很多,但我的程序总是跳入onErrorResponse方法。

我的代码:

private static String apiKey = "myAPIKey";
private static final String baseURI = "https://vision.googleapis.com/v1/images:annotate?fields=responses%2FfaceAnnotations&key=" + apiKey;


private static String exampleRequest = "{\"requests\":[{\"image\":{\"source\":{\"imageUri\":\"https://wikipedia.de/img/Wikipedia-logo-v2-de.svg\"}},\"features\":[{\"type\":\"TEXT_DETECTION\"}]}]}";



private static void testRequest(){
    JSONObject jsonObject = getJSONRequest(exampleRequest);
    Response.Listener<JSONObject> responseListener = getResponseListener();
    Response.ErrorListener errorListener = getErrorListener();

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(baseURIPost, jsonObject, responseListener, errorListener);
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(jsonObjectRequest);
}

private static Response.ErrorListener getErrorListener() {
    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    };
}

private static Response.Listener<JSONObject> getResponseListener() {
    return new Response.Listener() {
        @Override
        public void onResponse(Object response) {
        }
    };
}

private static JSONObject getJSONRequest(String json) {
    try {
        return new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}
android google-api http-post google-vision jsonobjectrequest
1个回答
0
投票

问题是API密钥没有添加计费。上面问题中的代码现在运行正常。

© www.soinside.com 2019 - 2024. All rights reserved.