如何在java中使用OAUTH对http post请求进行签名,并将JSON对象作为主体传递?
我需要调用一个restapipost方法,该方法接受两个参数username(可选查询参数),inputBody(JSON对象的必需参数,但不是JSON字符串),该参数将传递给“BODY”,而不是查询参数 以下是我打电话时遵循的步骤:如何在java中使用OAUTH对http post请求进行签名,并将JSON对象作为主体传递?,java,json,http-post,restapi,Java,Json,Http Post,Restapi,我需要调用一个restapipost方法,该方法接受两个参数username(可选查询参数),inputBody(JSON对象的必需参数,但不是JSON字符串),该参数将传递给“BODY”,而不是查询参数 以下是我打电话时遵循的步骤: 创建了用于对请求进行签名的oauth使用者对象和用于执行请求的httpclient对象 请求 使用json创建post请求 json_string = " {"id":"erv" , "age&quo
json_string = " {"id":"erv" , "age": 18 , "country" : "IND"} " // This is the json string
updatereq = new HttpPost("BASEURL/object");
updatereq.setHeader("Id","xyz");
StringEntity input = new StringEntity(json_string);
input.setContentType("application/json");
updatereq.setEntity(input);
catch(OAuthMessageSignerException e) {
e.printStackTrace();
}
catch(OAuthExpectationFailedException e) {
e.printStackTrace();
}
catch(OAuthCommunicationException e) {
e.printStackTrace();
}
`
updateresponse = httpClient.execute(updatereq);
int updatehttpResponseCode = updateresponse.getStatusLine().getStatusCode();
System.out.println("post Response Code :: " + updatehttpResponseCode);
if (updatehttpResponseCode == 200)
{
System.out.println("POST request worked);
}
else
{
System.out.println("POST request not worked");
}
```
POST请求未工作 我正在接收针对我正在发出的请求的“http错误请求”响应。 我如何解决这个问题? 我是否需要通过指定任何附加的头/参数来更改请求格式以使其生效?
我哪里做错了?请尝试添加以下行,好吗<代码>updatereq.setHeader(“接受”、“应用程序/json”);setHeader(“内容类型”、“应用程序/json”)代码>@Govind非常感谢男士:)它现在起作用了,帖子的回复是200。我仍然不明白json字符串是如何转换成json对象并在请求中作为正文发送的,但我的目的已经实现了。
updateresponse = httpClient.execute(updatereq);
int updatehttpResponseCode = updateresponse.getStatusLine().getStatusCode();
System.out.println("post Response Code :: " + updatehttpResponseCode);
if (updatehttpResponseCode == 200)
{
System.out.println("POST request worked);
}
else
{
System.out.println("POST request not worked");
}
```