Dav*_*ell 8 java rest resteasy
我正在使用RESTEasy客户端框架来调用RESTful Web服务.调用是通过POST进行的,并将一些XML数据发送到服务器.我该如何做到这一点?
用于实现这一目的的注释的神奇咒语是什么?
小智 12
我认为David指的是RESTeasy"客户端框架".因此,你的回答(Riduidel)并不是他所追求的.您的解决方案使用HttpUrlConnection作为http客户端.使用resteasy客户端而不是HttpUrlConnection或DefaultHttpClient是有益的,因为resteasy客户端是JAX-RS感知的.要使用RESTeasy客户端,可以使用其构造函数和方法构造org.jboss.resteasy.client.ClientRequest对象并构建请求.下面是我如何使用RESTeasy的客户端框架实现David的问题.
ClientRequest request = new ClientRequest("http://url/resource/{id}");
StringBuilder sb = new StringBuilder();
sb.append("<user id=\"0\">");
sb.append(" <username>Test User</username>");
sb.append(" <email>test.user@test.com</email>");
sb.append("</user>");
String xmltext = sb.toString();
request.accept("application/xml").pathParameter("id", 1).body( MediaType.APPLICATION_XML, xmltext);
String response = request.postTarget( String.class); //get response and automatically unmarshall to a string.
//or
ClientResponse<String> response = request.post();
Run Code Online (Sandbox Code Playgroud)
希望这有帮助,查理
就像下面一样简单
@Test
public void testPost() throws Exception {
final ClientRequest clientCreateRequest = new ClientRequest("http://localhost:9090/variables");
final MultivaluedMap<String, String> formParameters = clientCreateRequest.getFormParameters();
final String name = "postVariable";
formParameters.putSingle("name", name);
formParameters.putSingle("type", "String");
formParameters.putSingle("units", "units");
formParameters.putSingle("description", "description");
formParameters.putSingle("core", "true");
final ClientResponse<String> clientCreateResponse = clientCreateRequest.post(String.class);
assertEquals(201, clientCreateResponse.getStatus());
}
Run Code Online (Sandbox Code Playgroud)
我借用了这个例子:Build Restful service with RESTEasy下面的代码片段,它似乎完全符合你的要求,不是吗?
URL url = new URL("http://localhost:8081/user");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
StringBuffer sbuffer = new StringBuffer();
sbuffer.append("<user id=\"0\">");
sbuffer.append(" <username>Test User</username>");
sbuffer.append(" <email>test.user@test.com</email>");
sbuffer.append("</user>");
OutputStream os = connection.getOutputStream();
os.write(sbuffer.toString().getBytes());
os.flush();
assertEquals(HttpURLConnection.HTTP_CREATED, connection.getResponseCode());
connection.disconnect();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32689 次 |
| 最近记录: |