Android Http Post - Json - 响应错误错误请求

时间:2014-08-19 09:17:10

标签: android json

我试图向服务器发帖子。但我得到的只是一个答案:糟糕的要求。我真的很陌生。我已经做了一些其他的例子,但它没有用,但是没有。

服务器代码:

@RequestMapping(value="/restfulservice/alarm/start", method=RequestMethod.POST,
            headers={"Accept=application/json"})
    @ResponseStatus(HttpStatus.CREATED)
    public @ResponseBody AlarmStartResponse startAlarm(@RequestParam("alarmStartRequestJson") String alarmStartRequestJson,
                                                       @RequestParam("apiKey") String apiKey)

Android代码:

private class AsyncPOSTer extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://mydomain/restfulservice/alarm/start");
        try {
            List<NameValuePair> np = new ArrayList<NameValuePair>();
            np.add(new BasicNameValuePair("userId", "Jke"));
            np.add(new BasicNameValuePair("deviceId", "JkeOpo"));
            np.add(new BasicNameValuePair("pairedDeviceId", "JkeSam"));
            np.add(new BasicNameValuePair("name", "Jokke"));
            np.add(new BasicNameValuePair("telephoneNumber", "Phone"));
            np.add(new BasicNameValuePair("alarmInstructions", "alarm instructions"));
            np.add(new BasicNameValuePair("whenRaisedLatitude", "60.155229"));
            np.add(new BasicNameValuePair("whenRaisedLongitude", "15.199038"));
            np.add(new BasicNameValuePair("whenRaisedAccuracy", "33.000"));
            np.add(new BasicNameValuePair("streetAddress", "Biskopsv 7a"));
            np.add(new BasicNameValuePair("zipCode", "12345"));
            np.add(new BasicNameValuePair("city", "City"));
            np.add(new BasicNameValuePair("country", "Sweden"));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(np);
            post.setHeader("Accept", "application/json")
            post.setEntity(entity);

            HttpResponse response = client.execute(post);
            int responseCode = response.getStatusLine().getStatusCode();
            if (responseCode == 200) {
                Log.d(TAG, "200");
                return true;
            } else {
                Log.d(TAG, "NOT 200");
                return false;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您是否在浏览器中使用任何HTTP客户端尝试过相同的请求(在Chrome中使用POSTMAN,DHC等插件)?只是为了确保您传递了所需的JSON中的所有参数。

还有一个名为'REST Client for Android'的Android应用程序,您可以在其中创建HTTP请求并检查所有标头和参数是否正确。如果它在那里工作,它也应该在这里工作(考虑到你的代码是正确的)。

我不是为Android开发的,但我根据自己在其他平台上的经验告诉我。

答案 1 :(得分:0)

尝试更新

post.setHeader("Accept", "application/json")

post.setHeader("Content-Type", "application/json")

以JSON格式发送

相关问题