Java 415从jersey客户端调用post API时出错
我有下面的API返回访问令牌 职位 标题Java 415从jersey客户端调用post API时出错,java,jersey,jax-rs,jersey-2.0,jersey-client,Java,Jersey,Jax Rs,Jersey 2.0,Jersey Client,我有下面的API返回访问令牌 职位 标题中的内容类型为application/x-www-form-urlencoded。在正文中还包含以下参数 我发送用户名和密码,并通过基本身份验证进行保护。当我从邮递员那里打电话时,它提供访问令牌。当我使用HttpUrlConnection url = new URL(tokenURL); connection = (HttpURLConnection) url.openConnection(); con
中的内容类型为application/x-www-form-urlencoded
。在正文中还包含以下参数
我发送用户名和密码,并通过基本身份验证进行保护。当我从邮递员那里打电话时,它提供访问令牌。当我使用HttpUrlConnection
url = new URL(tokenURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", auth);
connection.setRequestProperty("Accept", "application/json");
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write("grant_type=client_credentials&scope=" + scope);
以上代码工作正常。但当我使用jersey时,它给出了415个错误。我正在使用下面的代码
谁能告诉我我在回复行中犯了什么错误。您需要在方法上设置Accept:
Response-Response=webTarget.request(MediaType.APPLICATION\u JSON)
.header(“内容类型”、“应用程序/x-www-form-urlencoded”)
.post(Entity.json(post));
您还需要确保,如果您的API接受应用程序/x-www-form-urlencoded
内容,这就是您要发送的内容
目前,您正在根据对Entity.json(post)
的使用情况发送application/json
内容
我不知道为post
指定了什么类型,但您需要弄清楚如何将其转换为a或a,然后使用表单
方法提交您的内容
Response-Response=webTarget.request(MediaType.APPLICATION\u JSON)
.header(“内容类型”、“应用程序/x-www-form-urlencoded”)
.post(实体表格(postForm))//假设postForm类型为Form或MultiValuedMap
猜测一下post
,将postForm
创建为一个多值map
可能会像下面这样简单(当然,您会在请求之前放置)
MultiValuedMap postForm=新的MultiValuedHashMap();
添加(“客户凭证”,范围);
您需要的是:
Response response= webTarget.request()
.accept("application/json") // Accept field from header of request
.header("Content-Type", "application/x-www-form-urlencoded") //manually set content-tyoe
.post(Entity.entity(input, MediaType.TEXT_PLAIN)); // request body
查看Jersey实际发送的内容的最佳方法是注册记录器,并记录网络。例如:
clientConfig.register(
new LoggingFeature(
new Slf4jLogger(this.getClass().getName(), null)));
Slf4jLogger来自
org.apache.cxf:cxf core
请编辑您的日志,而不是创建副本。实际上,我在这里提供了更多详细信息。我将删除旧的一个。你能帮忙吗。我真的很挣扎webtarget.request(“application/x-www-form-urlencoded”)这是干什么的?你没有设置这个连接。setRequestProperty(“Accept”,“application/json”);为什么?webTarget.request().header(“内容类型”、“应用程序/x-www-form-urlencoded”).header(“接受”、“应用程序/x-www-form-urlencoded”).post(Entity.json(post));菲利普,还有其他问题吗?我有这个错误。找不到媒体类型=应用程序/x-www-form-urlencoded的MessageBodyWriter,类型=class org.studyeasy.showroom.resources.PostDetails,genericType=class org.studyeasy.showroom.resources.PostDetails。请尝试使用标题(“内容类型”,“应用程序/x-www-form-urlencoded”)
设置内容类型。并使用MediaType.TEXT\u PLAIN
,以便选择文本编写器进行实体反序列化。
clientConfig.register(
new LoggingFeature(
new Slf4jLogger(this.getClass().getName(), null)));