Search code examples
androidhttp-postcloudsight

HTTPPost method with headers and body


I need to make a HTTPPost reguest on Cloudsight for image recognition purpose. I have:

BASE URL https://api.cloudsight.ai/v1/images

Headers: Content-Type  application/json
        Authorization  Cloudsight API_KEY

Its says: Send an image by using an HTTP POST request on the endpoint /images with either a multipart-form-encoded, or base64 encoded data parameter. url: http://docs.cloudsight.apiary.io/#reference/0/images-collection/send-an-image-for-identification?console=1 So far i have made this:

private class HTTPPOSTReguest extends AsyncTask<String, Void, String> {
        ProgressDialog dialog;
        String result = "";
        @Override

        protected void onPreExecute() {

        }

        @Override
        protected String doInBackground(String... params) {

            try {

                HttpResponse response = null;
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(BASE_URL);
                httppost.addHeader("Content-Type", "application/json");
                httppost.addHeader("Authorization", "CloudSight buEA_pC6K7FXT60inM2eUQ");

                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("images", encodedImage));
               httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                response = httpclient.execute(httppost);
                int responseCode = response.getStatusLine().getStatusCode();

                
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseBody = EntityUtils.toString(entity);
                    result = responseBody;
                }
            }  catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

Buth can seem to make a successful reguest. Can someone offer advice


Solution

  • A couple of things I noticed while looking through this. In the second snippet from the top, the Authorization header reads:

    Cloudsight API_KEY instead of CloudSight API_KEY

    Not sure if that was just a quick typo or if that's in the code. In the code sample, there's a line reading:

    HttpPost httppost = new HttpPost("https://api.cloudsightapi.ai");

    That should instead be:

    HttpPost httppost = new HttpPost("https://api.cloudsight.ai/v1/images");

    Give that a shot and let us know how it goes!