Java 如何使用 RESTEasy 客户端框架在 POST 中发送数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2877946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:58:19  来源:igfitidea点击:

How to use RESTEasy client framework to send data in a POST

javarestresteasy

提问by David Escandell

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?

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

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

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

回答by Riduidel

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

我从这个例子中借用了以下代码片段: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>[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();  

回答by Charles Akalugwu

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.

我认为大卫指的是 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();

Hope this helps, Charlie

希望这会有所帮助,查理

回答by daydreamer

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

回答by Doctor Eval

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.

我在弄清楚如何做到这一点时遇到了一些麻烦,所以我想我会把它贴在这里。使用 RESTeasy 代理客户端机制实际上非常简单。

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.

正如 Charles Akalugwu 所建议的那样,这种方法允许您创建一个可以在客户端和服务器端使用的单一 Java 接口,并生成明显且易于使用的客户端和服务器端代码。

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:

首先,为服务声明一个 Java 接口。这将在客户端和服务器端使用,并且应该包含所有 JAX-RS 声明:

@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:

要回答“如何使用 RESTEasy Client Framework 在 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);

To POST data to the service:

将数据POST到服务:

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.

自然地,如果您正在写入现有的 REST 服务,那么您可以通过为客户端编写 Java 接口来解决该问题。

回答by d0wn

Try this syntax:

试试这个语法:

Form form = new Form();
form
 .param(HttpHeaders.AUTHORIZATION, "Bearer " + token)
 .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)
 .post(entity);
System.out.println("HTTP code: " + response.getStatus());