具有Content-Type"*"的JAX-RS Jersey Read实体 [英] JAX-RS Jersey Read entity with Content-Type "*"

查看:221
本文介绍了具有Content-Type"*"的JAX-RS Jersey Read实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jax-RS向服务器发出请求,该服务器仅返回一个单词String,并将该响应读入String变量.问题是我不知道如何使用响应,因为它的Content-Type为*; charset=UTF-8(我使用Postman对此进行了验证). Jax-RS很难解析此类标头.这是我的代码:

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. The issue is that I have no idea how to use the response, as its Content-Type is *; charset=UTF-8 (I verified this using Postman). Jax-RS has difficulty parsing this kind of header. 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);

此POST请求有效.我得到了可以检查的实际响应.但是,当我尝试将此响应读取为String(代码的最后一行)时,会引发以下错误:

This POST request works. 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:

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)

我如何使Jax-RS正确阅读这种Content-Type?!?

How do I make Jax-RS properly read this kind of Content-Type?!?

推荐答案

我认为没有任何方法可以使Jersey/Jax-RS正确读取这种Content-Type.对于Jax-RS不喜欢的具有Content-Type的任何类型的Response,解决方案是简单地删除标头,并(如果需要)添加您自己的Content-Type标头,该标头更适合于Response.在尝试读取Response实体之前,请执行此操作.这解决了我的问题:

I do not think there is any way to get Jersey / Jax-RS to properly read that kind of 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. Do this BEFORE trying to read the Response entity. This fixed my issue:

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

这篇关于具有Content-Type"*"的JAX-RS Jersey Read实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆