如何解决如何使带有JSON对象的Java中用OAUTH签名的http发布请求作为主体传递?
我需要调用rest api post方法,该方法接受两个参数username(可选查询参数),inputBody(JSON对象的必需参数,而不是json字符串),该参数将传递给“ BODY”而不是查询参数。
这些是我拨打电话所遵循的步骤:
-
创建了一个用于对请求进行签名的oauth消费者对象,以及一个用于执行以下操作的httpclient对象: 请求
consumer = new CommonsHttpOAuthConsumer("abc","def"); requestConfig = RequestConfig.custom().setConnectTimeout(300 * 1000).build(); httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
-
使用json创建发布请求
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);
-
使用OAUTH凭据对请求进行签名
` 尝试{consumer.sign(updatereq); //签署请求}
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"); } ```
输出:
后响应代码:: 400
POST请求无效
我正在收到针对我提出的请求的“ http错误请求”响应。 我该如何解决这个问题? 我是否需要通过指定任何其他标头/参数来更改请求格式以使其工作? 我在哪里做错了?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。