Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 400错误请求-将JSON数据发布到RESTful控制器时_Java_Json_Rest_Spring Mvc - Fatal编程技术网

Java 400错误请求-将JSON数据发布到RESTful控制器时

Java 400错误请求-将JSON数据发布到RESTful控制器时,java,json,rest,spring-mvc,Java,Json,Rest,Spring Mvc,我试图将一些JSON数据发布到RESTful spring控制器。但得到400个错误请求作为响应状态 给出了我用于此目的的密钥配置文件中的以下代码: pom.xml依赖项: enter code here <properties> <org.springframework-version>4.1.4.RELEASE</org.springframework-version> </properties> <!-- Spring --&

我试图将一些JSON数据发布到RESTful spring控制器。但得到400个错误请求作为响应状态

给出了我用于此目的的密钥配置文件中的以下代码:

pom.xml依赖项:

enter code here <properties>
    <org.springframework-version>4.1.4.RELEASE</org.springframework-version>
</properties>

<!-- Spring -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${org.springframework-version}</version>
    <exclusions>
        <!-- Exclude Commons Logging in favor of SLF4j -->
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

<!-- Servlet -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.1</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<!-- json -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.1.1</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>
Beaconva:

public class BeaconVO {

private int no;

private String uuid;

public int getNo() {
    return no;
}

public void setNo(int no) {
    this.no = no;
}

public String getUuid() {
    return uuid;
}

public void setUuid(String uuid) {
    this.uuid = uuid;
}
}

客户端代码android

public class MainActivity extends Activity {
private static final String URL = "http://192.168.1.24:8080/test/api/beacons";
Button btnGet, btnPost;
TextView tv;

JSONObject json;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnGet = (Button) findViewById(R.id.btnGet);
    btnPost = (Button) findViewById(R.id.btnPost);
    tv = (TextView) findViewById(R.id.tv);

    btnGet.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    try {
                        String jsonData = getJSONData(URL, "GET");
                        if (jsonData == null || jsonData.isEmpty()) {
                            return;
                        }
                        JSONArray jsonArray = new JSONArray(jsonData);
                        json = jsonArray.getJSONObject(0);
                        StringBuilder sb = new StringBuilder();
                        sb.append("no / UUID\n");
                        for (int i = 0; i < jsonArray.length(); i++) {

                            JSONObject jsonObject = (JSONObject) jsonArray.get(i);

                            sb.append(jsonObject.getString("no") + " / " + jsonObject.getString("uuid"));
                            sb.append("\n");

                        }
                        setText(json.toString(), false);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        setText(e.toString(), true);
                    }
                }
            }).start();

        }
    });

    btnPost.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // setJSONData(URL, "POST", json.toString());
                    POST(URL, json.toString());
                }
            }).start();
        }
    });
}


public void POST(String strUrl, String jsonData) {
    try {
        URL url = new URL(strUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);// 5 secs
        connection.setReadTimeout(5000);// 5 secs

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");

        InputStream is = null;
        int status = connection.getResponseCode();
        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            is = connection.getErrorStream();
        } else {
            is = connection.getInputStream();
        }
        if (connection.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
        }
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());

        out.write(jsonData);
        out.flush();
        out.close();

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        connection.disconnect();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
        setText(e.toString(), true);
    }
}

private String getJSONData(String url, String method) {
    try {
        InputStream is = getInputStream(url, method);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        int bufferSize = 1024 * 1024;
        char[] readBuf = new char[bufferSize];
        int resultSize = 0;
        while ((resultSize = br.read(readBuf)) != -1) {
            if (resultSize == bufferSize) {
                sb.append(readBuf);
            } else {
                for (int i = 0; i < resultSize; i++) {
                    sb.append(readBuf[i]);
                }
            }
        }
        final String jsonData = sb.toString();
        setText(jsonData, false);

        is.close();
        return jsonData;
    } catch (Exception e) {
        e.printStackTrace();
        setText(e.toString(), true);
        return null;
    }
}


private InputStream getInputStream(String strUrl, String method) {
    InputStream is;
    try {
        log("getInputStream(" + strUrl + ", " + method + ")");
        URL url = new URL(strUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod(method);
        connection.setRequestProperty("Accept", "application/json");

        int status = connection.getResponseCode();
        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            is = connection.getErrorStream();
        } else {
            is = connection.getInputStream();
        }
        if (connection.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
        }

    } catch (Exception e) {
        e.printStackTrace();
        setText(e.toString(), true);
        return null;
    }
    return is;
}

StringBuilder sb = new StringBuilder();

private void setText(final String msg, final boolean isError) {
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            if (isError) {
                sb.append(msg);
                sb.append("\n");
                tv.setText("\n-------------------\n"+sb.toString());
            } else {
                tv.setText(msg);
            }
        }
    });
}
}


请帮助我。

负载主体可能无法设置为映射到Beaconva对象

GET请求有效吗?你能给我看一下Beaconva的课程吗?日志中也应该有更多信息。我认为您的请求缺少内容类型标题。内容类型:application/jsonGET请求运行良好。我添加了BeaConva是否启用了安全性?我不触摸安全设置我已经检查了BeaConva字段。并尝试删除@RequestBody,但得到500个错误请求作为响应状态。我很确定JSON无法映射到此对象。在这个有效负载{no:1 uuid:123}中,1后面应该有一个逗号。除了json中缺少逗号和注释中指出的缺少标题内容类型:application/json之外,这应该很有效。对不起,伙计们,我的问题是Beaconva中的setter方法。感谢您的建议我们也遇到了同样的问题,并通过明确定义默认构造函数进行了修复。如果重载构造函数,请确保提供默认构造函数以避免此问题。
    URL:http: // localhost:8080/test/api/beacons

    Method:
    POST

    Headers:Accept:application/
    json

    Payload:

{
    "no": 1 ,
    "uuid": "123"
    }
public class BeaconVO {

private int no;

private String uuid;

public int getNo() {
    return no;
}

public void setNo(int no) {
    this.no = no;
}

public String getUuid() {
    return uuid;
}

public void setUuid(String uuid) {
    this.uuid = uuid;
}
public class MainActivity extends Activity {
private static final String URL = "http://192.168.1.24:8080/test/api/beacons";
Button btnGet, btnPost;
TextView tv;

JSONObject json;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnGet = (Button) findViewById(R.id.btnGet);
    btnPost = (Button) findViewById(R.id.btnPost);
    tv = (TextView) findViewById(R.id.tv);

    btnGet.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    try {
                        String jsonData = getJSONData(URL, "GET");
                        if (jsonData == null || jsonData.isEmpty()) {
                            return;
                        }
                        JSONArray jsonArray = new JSONArray(jsonData);
                        json = jsonArray.getJSONObject(0);
                        StringBuilder sb = new StringBuilder();
                        sb.append("no / UUID\n");
                        for (int i = 0; i < jsonArray.length(); i++) {

                            JSONObject jsonObject = (JSONObject) jsonArray.get(i);

                            sb.append(jsonObject.getString("no") + " / " + jsonObject.getString("uuid"));
                            sb.append("\n");

                        }
                        setText(json.toString(), false);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        setText(e.toString(), true);
                    }
                }
            }).start();

        }
    });

    btnPost.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // setJSONData(URL, "POST", json.toString());
                    POST(URL, json.toString());
                }
            }).start();
        }
    });
}


public void POST(String strUrl, String jsonData) {
    try {
        URL url = new URL(strUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);// 5 secs
        connection.setReadTimeout(5000);// 5 secs

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");

        InputStream is = null;
        int status = connection.getResponseCode();
        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            is = connection.getErrorStream();
        } else {
            is = connection.getInputStream();
        }
        if (connection.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
        }
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());

        out.write(jsonData);
        out.flush();
        out.close();

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        connection.disconnect();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
        setText(e.toString(), true);
    }
}

private String getJSONData(String url, String method) {
    try {
        InputStream is = getInputStream(url, method);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        int bufferSize = 1024 * 1024;
        char[] readBuf = new char[bufferSize];
        int resultSize = 0;
        while ((resultSize = br.read(readBuf)) != -1) {
            if (resultSize == bufferSize) {
                sb.append(readBuf);
            } else {
                for (int i = 0; i < resultSize; i++) {
                    sb.append(readBuf[i]);
                }
            }
        }
        final String jsonData = sb.toString();
        setText(jsonData, false);

        is.close();
        return jsonData;
    } catch (Exception e) {
        e.printStackTrace();
        setText(e.toString(), true);
        return null;
    }
}


private InputStream getInputStream(String strUrl, String method) {
    InputStream is;
    try {
        log("getInputStream(" + strUrl + ", " + method + ")");
        URL url = new URL(strUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod(method);
        connection.setRequestProperty("Accept", "application/json");

        int status = connection.getResponseCode();
        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            is = connection.getErrorStream();
        } else {
            is = connection.getInputStream();
        }
        if (connection.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
        }

    } catch (Exception e) {
        e.printStackTrace();
        setText(e.toString(), true);
        return null;
    }
    return is;
}

StringBuilder sb = new StringBuilder();

private void setText(final String msg, final boolean isError) {
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            if (isError) {
                sb.append(msg);
                sb.append("\n");
                tv.setText("\n-------------------\n"+sb.toString());
            } else {
                tv.setText(msg);
            }
        }
    });
}