如何使用RESTEasy客户端框架以POST方式发送数据

9
我正在使用RESTEasy客户端框架调用RESTful webservice。通过POST方式发送一些XML数据到服务器。我该如何完成这个操作?
有哪些神奇的注解可以使用来实现这个操作?

@David Escandell,请您在此处发布完整的示例。我能够使用xml发布数据,但无法正确序列化对象。我希望您的示例能够对我有所帮助。 - user997961
2
我喜欢这个问题中的“注释的神奇咒语”部分……它是这种新工程现象中最棒的部分之一! - Darrell Teague
5个回答

13
我认为David指的是RESTeasy "Client Framework"。因此,你的答案(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();

希望这能有所帮助, Charlie


确实有所帮助。我找到的解决方案甚至更简单。该框架允许您构建一个Java接口,定义您要调用的REST方法。您可以在方法前面放置@Produces(“application / xml”),然后传入具有适当JAXB注释的对象,一切都会神奇地运行。 - David Escandell
当然可以!这种调用方式使用了RESTeasy客户端代理。你可以称之为另一种制作restful服务的“客户端框架”。我甚至更喜欢这种方法,因为它允许你在客户端上重用来自服务器的服务接口,从而拥有更容易自我记录和统一的API。 - Charles Akalugwu

5

只需按照以下简单步骤即可轻松完成

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

2
尝试使用以下语法:
Form form = new Form();
form
 .param("client_id", "Test_Client")
 .param("grant_type", "password")
 .param("response_type", "code")
 .param("scope", "openid")
 .param("redirect_uri", "some_redirect_url");
Entity<Form> entity = Entity.form(form);
    
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost:8080/auth/realms");
Response response = target
 .request(MediaType.APPLICATION_JSON)
 .header(HttpHeaders.AUTHORIZATION, authCreds)
 .post(entity);

System.out.println("HTTP code: " + response.getStatus());

我尝试为水壶服务运行此代码,但是它给了我302错误。 - qleoz12

1
我曾经在这方面遇到一些麻烦,所以我想在这里发布一下。使用RESTeasy代理客户端机制实际上非常容易。正如Charles Akalugwu建议的那样,这种方法允许您创建一个单独的Java接口,您可以在客户端和服务器端都使用它,并且会产生明显且易于使用的客户端和服务器端代码。首先,为服务声明一个Java接口。这将在客户端和服务器端都使用,并应包含所有JAX-RS声明。
@Path("/path/to/service")
public interface UploadService
{
  @POST
  @Consumes("text/plan")
  public Response uploadFile(InputStream inputStream);
}

接下来,编写一个实现此接口的服务器。它和看起来一样简单:

public class UploadServer extends Application implements UploadService
{
  @Override
  public Response uploadFile(InputStream inputStream)
  {
    // The inputStream contains the POST data
    InputStream.read(...);

    // Return the location of the new resource to the client:
    Response.created(new URI(location)).build();
  }
}

要回答“如何使用RESTEasy客户端框架发送POST数据”的问题,您只需要通过RESTeasy代理从客户端调用服务接口,RESTeasy将为您执行POST。创建客户端代理的方法如下:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://path/to/service");
ResteasyWebTarget rtarget = (ResteasyWebTarget)target;
UploadService uploadService = rtarget.proxy(UploadService.class);

将数据POST到服务中:
InputStream inputStream = new FileInputStream("/tmp/myfile");
uploadService.uploadFile(inputStream);

如果您要编写与现有REST服务交互的程序,可以通过为客户端编写一个Java接口来解决问题。


0
我从这个例子中借鉴了以下代码片段:使用RESTEasy构建RESTful服务,它似乎正好做到了你想要的,是吧?
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();  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接