将Json从Android发送到Spring Controller

时间:2017-12-23 17:51:46

标签: android json spring

当我尝试将JSONObject从Android App发送到Spring Controller时,我遇到了问题。我的意思是在客户端我将用户数据写入JSONObject并希望以POST方式发送它。它按照我的预期工作,但是括号字符(例如"{")和其他类似引号的符号会被转换为其他字符。

JSONObject:

{"name":"john","surname":"smith","email":"email@email.com","password":"123"}

转换为:

"%7B%22name%22%3A%22john%22%2C%22surname%22%3A%22smith%22%2C%22email%22%3A%22email%40email.com%22%2C%22password%22%3A%22123%22%7D="

我试图找到一个解决方案但你们现在我在这里。 我的代码来自android和controller:

@RequestMapping(value = "/registration", method = RequestMethod.POST)
public @ResponseBody String registerUserAccount(@RequestBody String userJson) {
    System.out.println(userJson);
    return userJson;
}

和Android部分:

    public class RegisterAsyncTask extends AsyncTask<String, Void, String> {
    private URL url;

    @Override
    protected String doInBackground(String... strings) {

        try {
            url = new URL(ServerProperties.REGISTER_URL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(ServerProperties.CONNECT_AND_READ_TIMEOUT);
            conn.setReadTimeout(ServerProperties.CONNECT_AND_READ_TIMEOUT);

            JSONObject jsonObject = JSONHelper.createRegisterJsonObject(name, surname, email, password);

            System.out.println(jsonObject.toString());

            OutputStream outputStream = conn.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            bufferedWriter.write(jsonObject.toString());

            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                Intent loggedScreenIntent = new Intent(RegisterActivity.this, LoginActivity.class);
                RegisterActivity.this.startActivity(loggedScreenIntent);

                return ServerHelper.getResponseMessage(conn.getInputStream());

            } else {
                System.out.println(ServerMessages.FALSE_EXCEPTION_MESSAGE + responseCode);
                return ServerMessages.FALSE_EXCEPTION_MESSAGE + responseCode;
            }

        } catch (Exception e) {
            return ServerMessages.EXCEPTION_MESSAGE + e.getMessage();
        }
    }

    @Override
    protected void onPostExecute(String result) {
        System.out.println(result);
    }
}

对不起我的英文,感谢您的帮助:)

0 个答案:

没有答案