如何使带有JSON对象的Java中用OAUTH签名的http发布请求作为主体传递?

问题描述

我需要调用rest api post方法,该方法接受两个参数username(可选查询参数),inputBody(JSON对象的必需参数,而不是json字符串),该参数将传递给“ BODY”而不是查询参数。

这些是我拨打电话所遵循的步骤:

  1. 创建了一个用于对请求进行签名的oauth消费者对象,以及一个用于执行以下操作的httpclient对象: 请求

      consumer = new CommonsHttpOAuthConsumer("abc","def");
      requestConfig = RequestConfig.custom().setConnectTimeout(300 * 1000).build();
      httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    
  2. 使用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);
    
  3. 使用OAUTH凭据对请求进行签名

    ` 尝试{consumer.sign(updatereq); //签署请求}

         catch(OAuthMessageSignerException e) {
             e.printStackTrace();
           }
         catch(OAuthExpectationFailedException e) {
             e.printStackTrace();
         }
         catch(OAuthCommunicationException e) {
             e.printStackTrace();
         }
      `
    
  4. 最终执行请求以获取响应代码

      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 (将#修改为@)