使用java发布json

时间:2015-12-28 22:09:29

标签: java json

我正在尝试发布此JSON以创建模拟服务:

{
  "port": "9091",
  "protocol": "http",
  "stubs": [
    {
      "responses": [
        {
          "is": {
            "headers": {
               "Content-Type": "application/json"
            },
            "statusCode": 200,
            "body": "{
                      \"type\": \"simpleRefno\"

              }"
          }
        }
      ],
      "predicates": [
        {
          "and": [
            {
              "equals": {
                "method": "GET"
              }
            },
            {
              "contains": {
                "path": "fortune_cookie"
              }
            },
            {
              "deepEquals": {
                "query": {
                  "type": "latest"
                }
              }
            }
          ]
        }
      ]
    }
  ]
}

并发布上面给出的json文件,我在下面给出了代码 -

public class Test {

    public static void main(String[] args) throws Exception {

         String t =getStringFromInputStream( );
        // System.out.println(t);
         sendPost( t);

    }

    private static String getStringFromInputStream( ) throws IOException {

        // The name of the file to open.

        Path path = FileSystems.getDefault().getPath("//TestFactory//mbjson//", "newres1.json");

        String contents  = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        return contents;
    }




    private static void sendPost(String urlParameter) throws Exception {

        String url = "http://127.0.0.1:2525/imposters";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = urlParameter;
        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());

    }

}

这是为我的应用程序创建一个模拟Web服务,这适用于HTML和XML类型,因为我移动到json类型,我无法POST给json我的模拟服务器。

下面是我面临的错误 -

Sending 'POST' request to URL : http://127.0.0.1:2525/imposters
Exception in thread "main" Post parameters : {
  "port": "9091",
  "protocol": "http",
  "stubs": [
    {
      "responses": [
        {
          "is": {
            "headers": {
               "Content-Type": "application/json"
            },
            "statusCode": 200,
            "body": "{
                      \"type\": \"simpleRefno\"

              }"
          }
        }
      ],
      "predicates": [
        {
          "and": [
            {
              "equals": {
                "method": "GET"
              }
            },
            {
              "contains": {
                "path": "fortune_cookie"
              }
            },
            {
              "deepEquals": {
                "query": {
                  "type": "latest"
                }
              }
            }
          ]
        }
      ]
    }
  ]
}

Response Code : 400
java.io.IOException: Server returned HTTP response code: 400 for URL: http://127.0.0.1:2525/imposters
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1676)
    at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1674)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1672)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245)
    at com.capitalone.mountebank.Test.sendPost(Test.java:65)
    at com.capitalone.mountebank.Test.main(Test.java:24)
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: http://127.0.0.1:2525/imposters
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
    at com.capitalone.mountebank.Test.sendPost(Test.java:59)
    ... 1 more

1 个答案:

答案 0 :(得分:0)

来自服务器的400响应代码表示“错误请求”。

1)插入

con.setRequestProperty("Content-Type","application/json");

下面设置其他请求属性和HTTP POST请求方法。

2)删除“body”字段中括号外的引号

因此,在您提供的错误消息中,它应该是

"body": {
   "type": "depositAccountTransaction"
}

并且在您提供的原始JSON文件中应该是

"body": {
   "type": "simpleRefno"
}

这也将消除在嵌套引号上使用转义序列的需要。