使用JSON对象作为有效负载对REST API的POST请求 [英] POST request to REST API with JSON object as payload

查看:234
本文介绍了使用JSON对象作为有效负载对REST API的POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用具有JSON有效负载的POST请求从REST API获取JSON响应(应在发送之前转换为URL编码文本)。我已经按照一些教程来实现该过程,但是我收到状态码400的错误。我可能没有编码给定的JSON字符串或遗漏了某些东西。请帮我解决这个问题。谢谢。

I am trying to get the JSON response from the REST API using the POST request that has JSON payload (should be converted to URL encoded text before sending). I have followed some tutorials to implement the process but I get error with status code 400. I may not be encoding the given JSON string or missing something. Please help me solve this problem. Thanks.

这是我的代码

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


推荐答案

在关注了很多帖子和教程之后超过24小时我知道我没有正确发送我的URL参数。我还了解到使用 ApacheHttpClient 进行REST API调用相对容易一些。我解决了我的HTTP错误代码400并从服务器获得了响应。以下是我的问题的工作代码。

After following many posts and tutorials for more than 24 hours I got to know that I am not sending my URL parameters correctly. And also I learned that REST API call using ApacheHttpClient is comparatively easier. I resolved my HTTP error code 400 and got the response back from the server. Here is the working code for my issue.

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

这篇关于使用JSON对象作为有效负载对REST API的POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆