简体   繁体   English

如何使用JSONObject将JSONObject发布到RESTful服务并读取响应

[英]How to post JSONObject to RESTful service and read response using java

I am trying to call POST operation of the service with JSON request body and read JSON response. 我正在尝试使用JSON请求正文调用服务的POST操作并读取JSON响应。

I have below method to build the JSON request as JSONObject object. 我有以下方法来将JSON请求构建为JSONObject对象。

public class CashFundTransfer {
public JSONObject buildRequest(){
    JSONObject request = new JSONObject();
    request.put("dateTime", getDateTimeObj());
    request.put("businessDate", getBusinessDateObj());
    request.put("description", getDescriptionObj());
    request.put("transferAccount", buildTransferAccount());
    request.put("amount", buildAmount());
    request.put("businessUnit", buildBusinessUnit());
    request.put("status", buildStatus());
    request.put("recipient", buildRecipient());
    request.put("cashFundTransferee", buildCashFundTransferee());
    request.put("enteringAssoc", buildEnteringAssoc());
    request.put("approvingAssoc", buildApprovingAssoc());
    request.put("accountingDivision", buildAccountingDivision());
    return request;
   }
}

All methods that that I call in put return a JSONObject's object that is a child node of the parent. 我在put中调用的所有方法都返回一个JSONObject对象,该对象是父对象的子节点。

In my test class, I have the below code. 在我的测试课中,我有以下代码。 When I execute the code, service is recieving hashcode of the StringEntity object, instead of the content. 当我执行代码时,服务正在接收StringEntity对象的哈希码,而不是内容。

public class CFTTest {
   CashFundTransfer cft = new CashFundTransfer();
   JSONObject request = cft.buildRequest();
   System.out.println("request: "+request);

   public void callService() throws IOException{
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url);
        try {
          String inputString = request.toString();
          System.out.println("inputString 1: "+inputString);
          StringEntity input = new StringEntity(inputString);
          System.out.println("input: "+input);
          } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
          }
          input.setContentType("application/json");
          postRequest.setEntity(input);
          try {
               response = httpClient.execute(postRequest);
          } catch (ClientProtocolException e) {
                e.printStackTrace();
          } catch (IOException e) {
                e.printStackTrace();
          }
          System.out.println("response: "+response);
      }
}

Below is the console when I execute this code. 下面是我执行此代码时的控制台。

request: {"dateTime":"2016-12-04","businessDate":"2016-12-04","amount":      {"Value":200.0,"currency":{"code":"USD","description":"dollar"}},"businessUnit":{"number":5525,"name":"WMT","location":{"countryCode":"US"},"id":"0"},"recipient":{"name":{"fullName":"Samuel"}},"description":"Store Use 1","transferAccount":{"id":992},"accountingDivision":{"number":"1"},"enteringAssoc":{"id":"0"},"cashFundTransferee":{"id":"0","type":"OPERATOR"},"approvingAssoc":{"id":"0"},"status":{"code":"1"}}
inputString 1: {"dateTime":"2016-12-04","businessDate":"2016-12-04","amount":{"Value":200.0,"currency":{"code":"USD","description":"dollar"}},"businessUnit":{"number":5525,"name":"WMT","location":{"countryCode":"US"},"id":"0"},"recipient":{"name":{"fullName":"Samuel"}},"description":"Store Use 1","transferAccount":{"id":992},"accountingDivision":{"number":"1"},"enteringAssoc":{"id":"0"},"cashFundTransferee":{"id":"0","type":"OPERATOR"},"approvingAssoc":{"id":"0"},"status":{"code":"1"}}
input: org.apache.http.entity.StringEntity@737996a0
14:06:22.238 [main] DEBUG o.a.h.i.c.BasicClientConnectionManager - Get    connection for route {s}-   >https://nodejs.dev.cashfundtransfer.bofbua.prod.cloud.wal-mart.com
14:06:22.506 [main] DEBUG o.a.h.i.c.DefaultClientConnectionOperator - Connecting to nodejs.dev.cashfundtransfer.bofbua.prod.cloud.wal-mart.com:443
14:06:22.609 [main] DEBUG o.a.h.c.protocol.RequestAddCookies - CookieSpec selected: best-match
14:06:22.630 [main] DEBUG o.a.h.c.protocol.RequestAuthCache - Auth cache   not set in the context
14:06:22.630 [main] DEBUG o.a.h.c.p.RequestTargetAuthentication - Target auth state: UNCHALLENGED
14:06:22.631 [main] DEBUG o.a.h.c.p.RequestProxyAuthentication - Proxy auth state: UNCHALLENGED
14:06:22.631 [main] DEBUG o.a.h.impl.client.DefaultHttpClient - Attempt 1 to execute request
14:06:22.632 [main] DEBUG o.a.h.i.conn.DefaultClientConnection - Sending request: POST /api/cashfundtransfer/v1 HTTP/1.1
14:06:22.632 [main] DEBUG org.apache.http.wire -  >> "POST /api/cashfundtransfer/v1 HTTP/1.1[\r][\n]"
14:06:22.634 [main] DEBUG org.apache.http.wire -  >> "Content-Length: 475[\r][\n]"
14:06:22.634 [main] DEBUG org.apache.http.wire -  >> "Content-Type: text/plain; charset=ISO-8859-1[\r][\n]"
14:06:22.634 [main] DEBUG org.apache.http.wire -  >> "Host: nodejs.dev.cashfundtransfer.bofbua.prod.cloud.wal-mart.com[\r][\n]"
14:06:22.634 [main] DEBUG org.apache.http.wire -  >> "Connection: Keep-Alive[\r][\n]"
14:06:22.635 [main] DEBUG org.apache.http.wire -  >> "User-Agent: Apache-HttpClient/4.3.5 (java 1.5)[\r][\n]"
14:06:22.635 [main] DEBUG org.apache.http.wire -  >> "[\r][\n]"
14:06:22.635 [main] DEBUG org.apache.http.headers - >> POST /api/cashfundtransfer/v1 HTTP/1.1
14:06:22.635 [main] DEBUG org.apache.http.headers - >> Content-Length: 475
14:06:22.635 [main] DEBUG org.apache.http.headers - >> Content-Type: text/plain; charset=ISO-8859-1
14:06:22.635 [main] DEBUG org.apache.http.headers - >> Host: nodejs.dev.cashfundtransfer.bofbua.prod.cloud.wal-mart.com
14:06:22.635 [main] DEBUG org.apache.http.headers - >> Connection: Keep-Alive
14:06:22.635 [main] DEBUG org.apache.http.headers - >> User-Agent: Apache-HttpClient/4.3.5 (java 1.5)
14:06:22.636 [main] DEBUG org.apache.http.wire -  >> "{"dateTime":"2016-12-04","businessDate":"2016-12-04","amount":{"Value":200.0,"currency":{"code":"USD","description":"dollar"}},"businessUnit":{"number":5525,"name":"WMT","location":{"countryCode":"US"},"id":"0"},"recipient":{"name":{"fullName":"Samuel"}},"description":"Store Use 1","transferAccount":{"id":992},"accountingDivision":{"number":"1"},"enteringAssoc":{"id":"0"},"cashFundTransferee":{"id":"0","type":"OPERATOR"},"approvingAssoc":{"id":"0"},"status":{"code":"1"}}"
14:06:22.653 [main] DEBUG org.apache.http.wire -  << "HTTP/1.1 400 Bad Request[\r][\n]"
14:06:22.658 [main] DEBUG org.apache.http.wire -  << "content-type: application/json; charset=utf-8[\r][\n]"
14:06:22.659 [main] DEBUG org.apache.http.wire -  << "strict-transport-security: max-age=15768000[\r][\n]"
14:06:22.659 [main] DEBUG org.apache.http.wire -  << "x-frame-options: DENY[\r][\n]"
14:06:22.659 [main] DEBUG org.apache.http.wire -  << "x-xss-protection: 1; mode=block[\r][\n]"
14:06:22.659 [main] DEBUG org.apache.http.wire -  << "x-download-options: noopen[\r][\n]"
14:06:22.659 [main] DEBUG org.apache.http.wire -  << "x-content-type-options: nosniff[\r][\n]"
14:06:22.659 [main] DEBUG org.apache.http.wire -  << "cache-control: no-cache[\r][\n]"
14:06:22.660 [main] DEBUG org.apache.http.wire -  << "content-length: 197[\r][\n]"
14:06:22.660 [main] DEBUG org.apache.http.wire -  << "Date: Wed, 21 Dec 2016 20:06:23 GMT[\r][\n]"
14:06:22.660 [main] DEBUG org.apache.http.wire -  << "Connection: keep-alive[\r][\n]"
14:06:22.660 [main] DEBUG org.apache.http.wire -  << "[\r][\n]"
14:06:22.661 [main] DEBUG o.a.h.i.conn.DefaultClientConnection - Receiving response: HTTP/1.1 400 Bad Request
14:06:22.661 [main] DEBUG org.apache.http.headers - << HTTP/1.1 400 Bad Request
14:06:22.661 [main] DEBUG org.apache.http.headers - << content-type: application/json; charset=utf-8
14:06:22.661 [main] DEBUG org.apache.http.headers - << strict-transport-security: max-age=15768000
14:06:22.661 [main] DEBUG org.apache.http.headers - << x-frame-options: DENY
14:06:22.661 [main] DEBUG org.apache.http.headers - << x-xss-protection: 1; mode=block
14:06:22.661 [main] DEBUG org.apache.http.headers - << x-download-options: noopen
14:06:22.661 [main] DEBUG org.apache.http.headers - << x-content-type-options: nosniff
14:06:22.661 [main] DEBUG org.apache.http.headers - << cache-control: no-cache
14:06:22.661 [main] DEBUG org.apache.http.headers - << content-length: 197
14:06:22.662 [main] DEBUG org.apache.http.headers - << Date: Wed, 21 Dec 2016 20:06:23 GMT
14:06:22.662 [main] DEBUG org.apache.http.headers - << Connection: keep-alive
14:06:22.667 [main] DEBUG o.a.h.impl.client.DefaultHttpClient - Connection can be kept alive indefinitely
response: HTTP/1.1 400 Bad Request [content-type: application/json; charset=utf-8, strict-transport-security: max-age=15768000, x-frame-options: DENY, x-xss-protection: 1; mode=block, x-download-options: noopen, x-content-type-options: nosniff, cache-control: no-cache, content-length: 197, Date: Wed, 21 Dec 2016 20:06:23 GMT, Connection: keep-alive]

Unable to identify, where I am going wrong on this. 无法确定,我在哪里出错了。

I'm assuming that JSONObject comes from the JSON.simple third party (You should probably add this information in the question next time, as java does not have any standard way to deal with json, yet). 我假设JSONObject来自JSON.simple第三方(您可能下次应该在问题中添加此信息,因为Java尚无任何处理json的标准方法)。

You need to invoke JSONObject.toJSONString() to retrieve the json string, as such: 您需要调用JSONObject.toJSONString()来检索json字符串,如下所示:

String inputString = request.toJSONString();
System.out.printf("inputString 1: %s\n", inputString);
StringEntity input = new StringEntity(inputString);

Also, when dealing with web services, content types should match the content of the request. 同样,在处理Web服务时,内容类型应与请求的内容匹配。 If you use the StringEntity constructor with a single parameter, apache http client will assume the text/plain content type, which is incorrect. 如果将StringEntity构造函数与单个参数一起使用,则apache http客户端将采用text/plain内容类型,这是不正确的。 You should use: 您应该使用:

StringEntity input = new StringEntity(inputString, ContentType.APPLICATION_JSON);

It failed because of a typo in my request object. 由于我的请求对象中有错字而导致失败。 Its working fine now. 现在工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM