POST request for REST API with JSON object as payload

I am trying to get a JSON response from a REST API using a POST request that has a JSON payload (needs to be converted to URL encoded text before sending). I have followed some tutorials to implement the process, but I am getting an error with status code 400. I am unable to encode the given JSON string or am missing something. Please help me to solve this problem. Thank.

Here is my code

    try {
        URL url = new URL("https://appem.totango.com/api/v1/search/accounts/health_dist");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("app-token", "1a1c626e8cdca0a80ae61b73ee0a1909941ab3d7mobile+testme@totango.com");
        conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
        conn.setRequestProperty("X-Requested-With","XMLHttpRequest");

        String payload = "{\"terms\":[{\"type\":\"totango_user_scope\",\"is_one_of\":[\"mobile+testme@totango.com\"]}],\"group_fields\":[{\"type\":\"health\"}]}";

        OutputStream os = conn.getOutputStream();
        os.write(payload.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
        conn.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

      

+1


source to share


2 answers


After several posts and tutorials over 24 hours, I found out that I am not sending URL parameters correctly. I also found out that calling REST APIs using ApacheHttpClient is relatively easy. I resolved my HTTP 400 error code and received a response from the server. Here is a working code for my problem.



        try {
            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost("https://appem.totango.com/api/v1/search/accounts/health_dist");

            List<NameValuePair> headers = new ArrayList<NameValuePair>(); //ArrayList to store header parameters
            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); //ArrayList to store URL parameters

            urlParameters.add(new BasicNameValuePair("query","{\"terms\":[{\"type\":\"totango_user_scope\",\"is_one_of\":[\"mobile+testme@totango.com\"]}],\"group_fields\":[{\"type\":\"health\"}]}"));
            headers.add(new BasicNameValuePair("app-token", "1a1c626e8cdca0a80ae61b73ee0a1909941ab3d7mobile+testme@totango.com"));
            headers.add(new BasicNameValuePair("Accept", "application/json, text/javascript, */*; q=0.01"));
            headers.add(new BasicNameValuePair("X-Requested-With", "XMLHttpRequest"));
            httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));

            for (NameValuePair h : headers)
            {
                httpPost.addHeader(h.getName(), h.getValue());
            }

            response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatusLine().getStatusCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (response.getEntity().getContent())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {
            try{
                response.close();
                httpClient.close();
            }catch(Exception ex) {
                ex.printStackTrace();
            }
        }

      

0


source


The API you are calling requires a query parameter called "query = true | false".

URL url = new URL("https://appem.totango.com/api/v1/search/accounts/health_dist?query=true");

      



After adding this parameter, the HTTP request itself will successfully complete status code 200, but the REST call fails on the server side. Perhaps you need a different payload.

I suggest if you are new to REST try a REST client like POSTMan

-1


source







All Articles