gpt4 book ai didi

java - 从 Jersey 调用@POST

转载 作者:行者123 更新时间:2023-12-01 11:54:36 27 4
gpt4 key购买 nike

我能够在 Jersey 上获得@GET请求,相关代码如下

服务器代码

@Path("/Text")
@GET
public String Hello() {
System.out.println("Text Being print");
return "Abc";
}

@POST
@Path("/post/{name}/{gender}")
public Response createDataInJSON(@PathParam("name") String data, @PathParam("gender") String data2) {
System.out.println("Post Method 1");

JSONObject obj = new JSONObject();
obj.put("Name", data);
obj.put("Gender", data2);

return Response
.status(200)
.entity(obj.toJSONString())
.build();

}

当参数在 url 中传递时,@POST 也起作用。 (如上面代码段提到的)但是,当参数不是通过 url 发送时,它不起作用。就像下面的代码一样。

@POST
@Path("/post2")
public Response createDataInJSON2(@FormParam("action") String data) {
System.out.println("Post Method 2 : Data received:" + data);

JSONObject obj = new JSONObject();
obj.put("data", data);

return Response
.status(200)
.entity(obj.toJSONString())
.build();

}

问题可能出在服务的调用方式上。

//GET call (Plain Text)
System.out.println(service.path("Hello").accept(MediaType.TEXT_PLAIN).get(String.class));

//POST call (Param)
ClientResponse response = service.path("Hello/post/Dave/Male").post(ClientResponse.class);
System.out.println(response.getEntity(String.class));

//POST call (JSON)
String input = "hello";

ClientResponse response2 = service.path("Hello/post2").post(ClientResponse.class, input);
System.out.println(response2.getEntity(String.class));

谁能告诉我我在这里错过了什么?

最佳答案

尝试在 @POST 方法上添加 @Consumes (application/x-www-form-urlencoded) createDataInJSON2 并在请求中显式添加相同的 mime 类型 service.path( "Hello/post2").type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, input)

还要考虑到您的输入只是一个简单的字符串。看一下 MultivaluedMap

如果您在编码方面遇到问题,请查看这篇文章 https://stackoverflow.com/a/18005711/3183976

关于java - 从 Jersey 调用@POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28538891/

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