免责声明:我确实详尽地搜索了这个问题的答案,是的,我确实找到了另一个问题:https://stackoverflow.com/questions/10315728/how-to-send-parameters-as-formparam-to-webservice .但首先,这个问题是关于 Javascript 的,而我是在问 Java,其次,它没有答案。那么问题...
使用 RESTful 服务,将 @QueryParam
传递给 @GET
服务相当容易,因为您只需将变量名称/值对附加到 URL 并使用它从程序中访问服务器。有没有办法用 @FormParam
来做到这一点?
例如,假设我有以下 RESTful 服务:
@POST
@Produces("application/xml")
@Path("/processInfo")
public String processInfo(@FormParam("userId") String userId,
@FormParam("deviceId") String deviceId,
@FormParam("comments") String comments) {
/*
* Process stuff and return
*/
}
... 假设我在我的程序中的其他地方还有另一种方法,如下所示:
public void updateValues(String comments) {
String userId = getUserId();
String deviceId = getDeviceId();
/*
* Send the information to the /processInfo service
*/
}
如何在第二种方法中执行注释掉的操作?
注意:假设这些方法不在同一个类或包中。还假设 RESTful 服务托管在与您运行方法所在的机器不同的服务器上。因此,您必须访问该方法并以 RESTful 方式传递值。
感谢您的帮助!
最佳答案
使用@FormParam,您可以将表单参数绑定(bind)到一个变量。您可以找到示例 here .
其次,为了从您的 java 方法代码内部调用 rest 服务,您将必须使用 jersey 客户端。可以找到示例代码 here .
您可以使用 jersey 客户端表单传递表单参数,如下所示。
创建表单
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(UriBuilder.fromUri("http://localhost:8080/api").build());
Form f = new Form();
f.add("userId", "foo");
f.add("deviceId", "bar");
f.add("comments", "Device");
将其传递给 Restful 方法。
service.path("processInfo").accept(MediaType.APPLICATION_XML).post(String.class,f);
关于java - 如何从另一种方法将 @FormParam 传递给 RESTful 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12315778/