使用代理接口在RestEasy客户端框架中如何设置"Content-type"头?

3
我正在使用Resteasy客户端代理框架与REST API进行通信。我在代理接口上定义了一些方法,但不幸的是,在发送HTTP请求时,Content-Type未正确设置,这导致我收到http 400(错误请求)错误代码,因为远程API期望 Content-type头参数为application/json
以下是示例:
@Path("/")
public interface RestAPIClient {

  @POST
  @Path("/send")
  String send(@CookieParam("token") String token, @FormParam("name") String id, @FormParam("message") String message, @FormParam("emails") List<String> emails);

}

有没有直接在代理接口级别上设置“Content-type”标头为“application/json”的方法?可以使用一些注解吗?
谢谢。
2个回答

2

I you try a

@Consumes(MediaType.APPLICATION_JSON)

在POST中的处理需要注意以下几点:首先,你需要准备一个“实体”对象来发送到该方法(不是@CookieParam或@FormParam)。

因此,你的方法必须像这样:

@POST
@Path("/auth")
@Consumes(MediaType.APPLICATION_JSON)
ConnectionInformation auth(@CookieParam("name") String name, @CookieParam("password") String password, MyJSONObject entity);

并且,“entity”将会产生
Content-Type: application/json

you need.


我想我已经尝试过了,但它还是不起作用。我指定了纯字符串"application/json"而不是MediaType.APPLICATION_JSON,所以也许我应该尝试这个。让我们看看! - kaffein
不行,不起作用。MediaType.APPLICATION_JSON 只是 "application/json" 的别名。 - kaffein
1
已经根据建议进行了编辑 :) - twillouer

0

除了使用:

@Consumes(MediaType.APPLICATION_JSON)

你需要确保请求正文中实际上有内容(而不仅仅是参数)。

如果没有内容,则 Content-Type 标头将不会被设置。


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