有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用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类型,所以我无法将给定的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) 个答案

  1. # 1 楼答案

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

    1)插入

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

    下面是设置其他请求属性和HTTP POST请求方法的位置

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

    因此,在您提供的错误消息中

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

    在您提供的原始JSON文件中

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

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