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

发布于 2024-09-02 00:55:05 字数 119 浏览 1 评论 0原文

我正在使用 RESTEasy 客户端框架来调用 RESTful Web 服务。该调用是通过 POST 进行的,并将一些 XML 数据发送到服务器。我该如何实现这个目标?

使用注释来实现这一点的神奇咒语是什么?

I am using the RESTEasy client framework to call a RESTful webservice. The call is made via a POST and sends some XML data to the server. How do I accomplish this?

What is the magical incantation of annotations to use to make this happen?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

我家小可爱 2024-09-09 00:55:05

我认为 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>[email protected]</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();

希望这有帮助,
查理

I think David is referring to the RESTeasy "Client Framework". Therefore, your answer (Riduidel) is not particularly what he is looking for. Your solution uses HttpUrlConnection as the http client. Using the resteasy client instead of HttpUrlConnection or DefaultHttpClient is beneficial because resteasy client is JAX-RS aware. To use the RESTeasy client, you construct org.jboss.resteasy.client.ClientRequest objects and build up requests using its constructors and methods. Below is how I'd implement David's question using the client framework from RESTeasy.

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>[email protected]</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();

Hope this helps,
Charlie

梦过后 2024-09-09 00:55:05

就像下面一样简单

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

It is as easy as following

    @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());
    }
千秋岁 2024-09-09 00:55:05

试试这个语法:

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

Try this syntax:

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());
戏剧牡丹亭 2024-09-09 00:55:05

我在弄清楚如何执行此操作时遇到了一些困难,所以我想我会将其发布在这里。使用 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 将执行以下操作:为您发帖。创建客户端代理:

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 接口来解决该问题。

I had some trouble figuring out how to do this so I thought I would post it here. Using the RESTeasy proxy client mechanism is actually embarrassingly easy.

As Charles Akalugwu suggests, this approach allows you to create a single Java interface which you can use on both the client and server side, and results in both client- and server-side code that's obvious and easy to use.

First, declare a Java interface for the service. This will be used on both the client and server side, and should contain all of the JAX-RS declarations:

@Path("/path/to/service")
public interface UploadService
{
  @POST
  @Consumes("text/plan")
  public Response uploadFile(InputStream inputStream);
}

Next, write a server which implements this interface. It's as easy as it looks:

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

To answer the question "how to use RESTEasy Client Framework to send data in a POST", all you have to do is call the service interface from the client side via a RESTeasy proxy, and RESTeasy will do the POST for you. To create the client proxy:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://path/to/service");
ResteasyWebTarget rtarget = (ResteasyWebTarget)target;
UploadService uploadService = rtarget.proxy(UploadService.class);

To POST data to the service:

InputStream inputStream = new FileInputStream("/tmp/myfile");
uploadService.uploadFile(inputStream);

Naturally, if you are writing to an existing REST service then you could approach the problem by writing a Java interface just for the client.

嘿嘿嘿 2024-09-09 00:55:05

我借用了这个例子: 使用 RESTEasy 构建宁静的服务< /a> 下面的代码片段,似乎完全符合您的要求,不是吗?

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>[email protected]</email>");
sbuffer.append("</user>");

OutputStream os = connection.getOutputStream();
os.write(sbuffer.toString().getBytes());
os.flush();

assertEquals(HttpURLConnection.HTTP_CREATED, connection.getResponseCode());
connection.disconnect();  

I borrowed from this example : Build restful service with RESTEasy the following code fragment, which seems to do exactly what you want, no ?

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>[email protected]</email>");
sbuffer.append("</user>");

OutputStream os = connection.getOutputStream();
os.write(sbuffer.toString().getBytes());
os.flush();

assertEquals(HttpURLConnection.HTTP_CREATED, connection.getResponseCode());
connection.disconnect();  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文