Java 如何使用RestEasy将JSON发送到外部API?

Java 如何使用RestEasy将JSON发送到外部API?,java,json,resteasy,Java,Json,Resteasy,我需要向发送一个JSON正文。如何在Java中使用RestEasy实现这一点?这就是我到目前为止所做的: ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target("https://mandrillapp.com/api/1.0//messages/send-template.json"); 如何实际发送JSON?一旦您拥有了ResteasyWebT

我需要向发送一个JSON正文。如何在Java中使用RestEasy实现这一点?这就是我到目前为止所做的:

ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("https://mandrillapp.com/api/1.0//messages/send-template.json");

如何实际发送JSON?

一旦您拥有了
ResteasyWebTarget
,您就需要获得
调用

Invocation.Builder invocationBuilder = target.request("text/plain").header("some", "header");
Invocation incovation = invocationBuilder.buildPost(someEntity);
invocation.invoke();
其中,
someEntity
是的某个实例。创建一个

Entity<String> someEntity = Entity.entity(someJsonString, MediaType.APPLICATION_JSON);
Entity someEntity=Entity.Entity(someJsonString,MediaType.APPLICATION\u JSON);


这是针对3.0 beta 4的。

我从未使用过此框架,但根据的一个示例,您应该能够进行如下调用:

        Client client = ClientBuilder.newBuilder().build();
        WebTarget target = client.target("http://foo.com/resource");
        Response response = target.request().get();
        String value = response.readEntity(String.class);
        response.close();  // You should close connections!

第三行似乎就是你想要的答案

这是一个有点老的问题,但我发现它在谷歌上寻找类似的东西,所以这是我的解决方案,使用RestEasy client 3.0.16:

我将使用要发送的映射对象,但您可以使用任何可以转换为JSON的JavaBean

顺便说一句,您需要添加resteasy-jackson2-provider库作为依赖项

ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://server:port/api/service1");
Map<String, Object> data = new HashMap<>();
data.put("field1", "this is a test");
data.put("num_field2", 125);
Response r = target.request().post( Entity.entity(data, MediaType.APPLICATION_JSON));
if (r.getStatus() == 200) {
    // Ok
} else {
    // Error on request
    System.err.println("Error, response: " + r.getStatus() + " - "+ r.getStatusInfo().getReasonPhrase());
}
resteasyclientclient=new ResteasyClientBuilder().build();
ResteasyWebTarget=client.target(“http://server:port/api/service1");
映射数据=新的HashMap();
data.put(“field1”,“这是一个测试”);
数据输入(“num_field2”,125);
Response r=target.request().post(Entity.Entity(data,MediaType.APPLICATION_JSON));
if(r.getStatus()==200){
//嗯
}否则{
//请求时出错
System.err.println(“错误,响应:+r.getStatus()+”-“+r.getStatusInfo().GetReasonPhase());
}

谢谢。我已经去过那个网站很多次了,但我更感兴趣的是通过POST发送信息,而不是回复。这就是发送。所需的唯一区别是它调用的是
request().get()
,而不是
request().buildPost(…)
buildPost
的javadoc如下: