如何使用Spring for Android POST键/值对而不是JSON对象?

时间:2013-01-11 05:29:43

标签: android spring rest post http-post

我正在尝试使用Spring for Android对url执行标准HTTP POST,其中body只是一个参数列表(如键值对)而不是JSON对象。

我希望将响应从JSON转换为Java ResponseObject,但据我所知,Spring也将我的身体转换为JSON。

这是我的代码:

Map<String, Object> params = new HashMap<String, Object>();
    params.put("client_id", mClientId);
    params.put("state", mState);
    params.put("username", mUsername);
    params.put("password", mPassword);
    return getRestTemplate().postForObject(url, params, ResponseObject.class);

提前谢谢!

2 个答案:

答案 0 :(得分:4)

试试这个

发布简单的名称值对列表

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", nameString));
nameValuePairs.add(new BasicNameValuePair("Country", "country name"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
}catch (ClientProtocolException e) {
 // TODO Auto-generated catch block
}

答案 1 :(得分:2)

使用.exchange()

// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();     

body.add("client_id", mClientId); // and so on

// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

MyModel model = restTemplate.exchange("/api/url", HttpMethod.POST, httpEntity, MyModel.class);