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

时间:2017-02-20 08:11:10

标签: java json rest spring-mvc

我正在尝试将一些JSON数据发布到RESTful spring控制器。但是将“400 Bad Request”作为响应状态。

从我正在使用的关键配置文件中提供以下代码:

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>

调度-servlet.xml中:

    <beans:bean
    class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <beans:property name="messageConverters">
        <beans:list>
            <beans:ref bean="jsonConverter" />
            <!-- <ref bean="marshallingConverter" /> <ref bean="atomConverter" /> -->
        </beans:list>
    </beans:property>
</beans:bean>

<beans:bean id="jsonConverter"
    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <beans:property name="supportedMediaTypes" value="application/json" />
</beans:bean>

控制器类:

    @Controller
@RequestMapping("/api/beacons")
public class APIController {

    private static final Logger logger = LoggerFactory.getLogger(APIController.class);

    @Autowired
    BeaconService beaconService;

    @RequestMapping(method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public List<BeaconVO> listAllBeacons() {
        logger.info("/api/beacon GET");
        List beacons = beaconService.findList(new BeaconVO());
        return beacons;
    }

    @RequestMapping(method = RequestMethod.POST, consumes = "application/json")
    // @ResponseStatus(HttpStatus.NO_CONTENT)
    @ResponseBody
    public BeaconVO saveBeacon(@RequestBody BeaconVO beaconVO) {
        logger.info("/api/beacon POST");
        beaconService.register(beaconVO);
        return beaconVO;
    }

请求详细信息:

    URL:http: // localhost:8080/test/api/beacons

    Method:
    POST

    Headers:Accept:application/
    json

    Payload:

{
    "no": 1 ,
    "uuid": "123"
    }

BeaconVO:

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);
            }
        }
    });
}

}

请帮帮我。

1 个答案:

答案 0 :(得分:-2)

有效负载主体可能无法设置(映射)到BeaconVO对象。