简体   繁体   English

内容类型为“ *”的JAX-RS Jersey读取实体

[英]JAX-RS Jersey Read entity with Content-Type “*”

I am using Jax-RS to make a request to a server, which just returns a one word String, and read that response into a String variable. 我正在使用Jax-RS向服务器发出请求,该服务器仅返回一个单词String,并将该响应读入String变量。 The issue is that I have no idea how to use the response, as its Content-Type is *; charset=UTF-8 问题是我不知道如何使用响应,因为它的Content-Type是*; charset=UTF-8 *; charset=UTF-8 (I verified this using Postman). *; charset=UTF-8 (我使用邮递员对此进行了验证)。 Jax-RS has difficulty parsing this kind of header. Jax-RS很难解析此类标头。 Here is my code: 这是我的代码:

MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("username", username);
formData.add("target", "10");
Response response = target.request().accept(MediaType.APPLICATION_JSON_TYPE).post(Entity.form(formData));
String responseString = response.readEntity(String.class);

This POST request works. 此POST请求有效。 I get an actual Response that I can inspect. 我得到了可以检查的实际响应。 However, when I try to read this response into a String (last line of code), the following error is thrown: 但是,当我尝试将此响应读取为String(代码的最后一行)时,将引发以下错误:

org.glassfish.jersey.message.internal.HeaderValueException: Unable to parse "Content-Type" header value: "*; charset=UTF-8" ! at
org.glassfish.jersey.message.internal.InboundMessageContext.exception(InboundMessageContext.java:338) ! at
org.glassfish.jersey.message.internal.InboundMessageContext.singleHeader(InboundMessageContext.java:333) ! at
org.glassfish.jersey.message.internal.InboundMessageContext.getMediaType(InboundMessageContext.java:446) ! at
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:869)

How do I make Jax-RS properly read this kind of Content-Type?!? 如何使Jax-RS正确读取这种Content-Type ?!

I do not think there is any way to get Jersey / Jax-RS to properly read that kind of Content-Type. 我认为没有任何方法可以使Jersey / Jax-RS正确读取这种Content-Type。 A solution for any kind of Response that has a Content-Type that Jax-RS does not like is to simply remove the header and (if needed) add your own Content-Type header that is more appropriate for the Response. 对于具有Jax-RS不喜欢的Content-Type的任何类型的Response的解决方案是,只需删除标头,然后(如果需要)添加您自己的Content-Type标头,该标头更适合于Response。 Do this BEFORE trying to read the Response entity. 在尝试读取Response实体之前,请执行此操作。 This fixed my issue: 这解决了我的问题:

response.getHeaders().remove("Content-Type");
response.getHeaders().add("Content-Type", "text/plain");
String responseString = response.readEntity(String.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM