【问题标题】:How to POST key/value pairs instead of a JSON Object using Spring for Android?如何使用 Spring for Android 发布键/值对而不是 JSON 对象?
【发布时间】:2012-12-25 16:28:23
【问题描述】:

我正在尝试使用 Spring for Android 对 url 执行标准 HTTP POST,其中的主体只是参数列表(如键值对)而不是 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);

提前谢谢你!

【问题讨论】:

  • 您能提供预期的响应正文和当前响应正文吗?
  • applicationContext.xml 或类似配置文件中的 restTemplate 配置是什么
  • 您找到解决方案了吗?

标签: android spring rest post http-post


【解决方案1】:

使用.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);

【讨论】:

    【解决方案2】:

    试试这个

    发布简单的名称值对列表

    // 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 2021-08-29
      • 2020-01-10
      • 2017-08-17
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      相关资源
      最近更新 更多