gpt4 book ai didi

java - 在 GET Rest 资源中发送 JSON -curl 和代码具有不同的行为

转载 作者:行者123 更新时间:2023-12-01 05:14:37 26 4
gpt4 key购买 nike

我首先会说:我正在做一些非常错误的事情。这就是我做错的事情。

我创建了一个 REST 资源来搜索某些内容,并且我期望请求参数中包含 JSON 数据:

@GET
@Path("/device")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response searchContent(String searchJSONString) {
String message = new SearchServices().search(searchJSONString);

return getResponse(message); //Checks the message for any error and sends back the response.
}//end of searchContent()

我不应该写:

@Consumes

因为它是一个 GET 资源并且不消耗任何东西。但我的问题是如何在 java 代码中发送 JSON 数据(GET 资源)。我尝试了curl命令,它能够将JSON数据发送到该资源,但无论如何都不能发送java代码。

我尝试按照curl命令向其发送JSON数据:

curl -X GET -H "Content-Type: application/json" -d '{"keyword":"hello"}' http://localhost:8080/search-test/rest/search

它工作正常,并给我返回了正确的 JSON 响应。

但是如果我使用curl命令而不指定任何方法(这应该是默认的http get),我会从tomcat收到405(方法不允许)响应:

curl -d '{"keyword":"hello"}' http://localhost:8080/search-test/rest/search

或者通过Java代码:

HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("GET"); //This is not working.

从 tomcat 获取相同的 405(方法不允许)响应。

如果我使用 java 代码发送 GET 请求,我无法像在 post 方法中那样发送 JSON 数据,并且我被迫使用 name=value 事物,为此我需要更改我的 REST 资源接受它作为名称/值对。

它的意思是这样的:

http://localhost:8080/search-test/rest/search?param={"keyword":"permission"}

如果我在 POST 中做类似的事情:

@POST
@Path("/device")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response searchContent(String searchJSONString) {
String message = new SearchServices().search(searchJSONString);

return getResponse(message); //Checks the message for any error and sends back the response.
}//end of searchContent()

我也可以从 Java 代码和curl 命令发送 JSON 数据:

curl -X POST -H "Content-Type: application/json" -d '{"keyword":"hello"}' http://localhost:8080/search-test/rest/search

或者通过Java代码:

HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
urlConnection.setRequestMethod("POST"); //Works fine.
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setDoOutput(true);

问题出在哪里?为什么我不能从代码发送它而是从curl发送它?除了 name=value 对之外,还有其他方法可以将 JSON 数据发送到 GET 资源吗?

最佳答案

HttpURLConnection 不允许使用实体进行 GET 请求,并且会在将请求发送到服务器之前将实体从请求中删除。因此,我强烈建议避免它,因为即使您使用允许您执行此操作的不同 Java HTTP 客户端库,您的用户也可能会遇到类似的问题(加上 Web 缓存和代理可能会增加更多问题)。

关于java - 在 GET Rest 资源中发送 JSON -curl 和代码具有不同的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11447943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com