2016-12-21 1 views
0

Я пытаюсь вызвать службу POST службы с телом запроса JSON и прочитать ответ JSON.Как отправить сообщение JSONObject в службу RESTful и прочитать ответ с помощью java

У меня есть метод ниже, чтобы построить запрос 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; 
    } 
} 

Всех методы, которые я называю в путах возвращают объект JSONObject, что является дочерним узлом родителя.

В моем тестовом классе у меня есть код ниже. Когда я выполняю код, служба получает хэш-код объекта 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); 
     } 
} 

Ниже приведена консоль при выполнении этого кода.

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: [email protected] 
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] 

Невозможно определить, где я ошибаюсь.

+0

Я уверен, что 'JSONObject.toString()' не возвращает строку json. Вам нужно использовать 'JSONObject.toJSONString()'. – sturcotte06

ответ

0

Я предполагаю, что JSONObject принадлежит JSON.simple третьей стороне (вероятно, вы должны добавить эту информацию в вопрос в следующий раз, поскольку java не имеет стандартного способа обработки json, пока).

Вам нужно вызвать JSONObject.toJSONString(), чтобы получить строку JSON, как таковой:

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

Кроме того, при работе с веб-службами, типы контента должны соответствовать содержанию запроса. Если вы используете конструктор StringEntity с одним параметром, клиент http-apache будет использовать тип содержимого text/plain, что неверно. Вы должны использовать:

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

Это также касается вашего сообщения. Я заметил, что ваш 'Content-Type' является' text/plain'. Вызов 'postRequest.setHeader (« Content-Type »,« application/json »)' – jiveturkey

+0

@ sturcotte06 Я сделал оба изменения, но я не вижу никаких изменений в поведении. Когда я запускаю его при отладке, в 'postRequest.setEntity (input);' значение во входном файле отражает хэш-код, а не тело JSON. – Naresh

0

Это не удалось из-за опечатки в моем объекте запроса. Теперь он работает отлично.

Смежные вопросы