簡體   English   中英

400錯誤的請求-將JSON數據發布到RESTful控制器時

[英]400 Bad Request - while POSTing JSON data to RESTful controller

我試圖將一些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>

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

}

請幫我。

有效負載主體可能無法設置(映射)為BeaconVO對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM