当前位置: 首页 > 面试题库 >

以JSON对象作为有效载荷的REST API的POST请求

徐昆
2023-03-14
问题内容

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

这是我的代码

    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,并从服务器获取了响应。这是我的问题的工作代码。

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


 类似资料:
  • 我在Kafka中有这样的配置 我有一个类,有相同的有效负载代码,我如何在任何时候在对象中转换它? 大家好,我有一个微服务接收这个字符串并且正在工作,但是我需要将这个字符串转换为一个特定的对象,当我使用ObjectMapper转换应用程序时,会返回这个异常: 抛出异常;嵌套异常是com.fasterxml.jackson.databind.exc.InvalidDefinitionException

  • 问题内容: 我正在使用 PHP , ExtJS 和 ajax存储 。 它不通过POST或GET发送数据(在创建,更新,销毁时)。在 Chrome控制台中, 我在“ 请求有效负载 ”字段中看到我的传出参数为JSON 。 $ _POST 和 $ _GET 为空。 如何在PHP中检索它? 问题答案: 如果我正确理解这种情况,那么您只是通过http正文传递了json数据,而不是数据。 您可以使用以下代码段

  • 有人能帮我吗?提前谢了。

  • 问题内容: 我正在使用文件上传器,并且需要请求有效负载中的详细信息以进行裁剪。 我没有10位代表来发布POST请求的图片,但是它有 所以从avatar_data我所需要的,,,和。我知道我必须封送JSON,但是我不确定如何达到这一点? 问题答案: 实现接口。

  • 我试图向服务器发出POST请求,但我遇到了一个问题。服务器似乎收到了请求,但我仍然在控制台中看到一个错误,建议将主体从Object更改为JSON 错误:SyntaxError:JSON中位于JSON位置0处的意外标记A。在XMLHttpRequest处解析()。装载(http://localhost:4200/vendor.js:69142:51)text:“它是用id=:23保存的新用户”pro

  • 我创建了一个带有参数的API,如下所示: 我在body->表单数据中传递了。 然后我在《邮递员》上得到了这样一条消息: 有人知道为什么会有这个消息吗?我们如何在Rest API请求中传递一个映射作为参数?我们怎样才能通过邮递员传递地图?