Search code examples
androidgoogle-apihttp-postgoogle-visionjsonobjectrequest

How to send an API-request to google via JsonObjectRequest?


I'd like to test the cloud vision API in my Android application.

The API is activated and it works in the Google Cloud Explorer like the image below shows.

Google APIs Explorer

How can I make a simple post request by a RequestQueue-object?

I tried a lot of but my program always jumps in the onErrorResponse method.

my code:

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;
}

Solution

  • The problem was that there was no billing added to the API-key. The code in the question above works fine now.