【问题标题】:Retrieving JSON data via HTTP POST using Spring Android Framework使用 Spring Android 框架通过 HTTP POST 检索 JSON 数据
【发布时间】:2013-02-19 11:56:19
【问题描述】:

我正在使用 spring android 框架通过 Http POST 检索 json 数据。但是在使用服务时,在服务器端接收到的参数为空。

以下是安卓代码:

protected String doInBackground(String... params) {
String username = params[0];

String password = params[1];

String url = connectServices.connectLoginServiceURL();// returns url

loginServiceParam = new LinkedMultiValueMap<String, String>();
loginServiceParam.add("username", username);
loginServiceParam.add("password", password); //username and password are null at server end.

HttpHeaders requestHeaders = new HttpHeaders();

requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
requestHeaders.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(loginServiceParam, requestHeaders);

// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();

// Add the Gson message converters
restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

// Make the HTTP POST request, marshaling the response from JSON

ResponseEntity<LoginBean> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, LoginBean.class);

LoginBean loginBeanResponse = responseEntity.getBody();

status = loginBeanResponse.getStatus();

return status;
}

LoginBean 类如下:

public class LoginBean {

    private String status;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

json 响应是:

{"status":"true"}

谢谢!

【问题讨论】:

    标签: android spring-3 resttemplate rest-client


    【解决方案1】:

    我自己解决了这个问题。 以下代码需要放

    RestTemplate restTemplate = new RestTemplate(true);
    

    POST 请求需要 True。 默认情况下,它是 false 并且用于 GET 请求。 即使在Spring Android Reference link 上也没有提到这一点

    【讨论】:

    • Arpit,这是不正确的。 true 参数与 POST 或 GET 请求无关。将true 传递给新的 RestTemplate 实例表示添加一组默认消息转换器。请参阅此处的参考文档:static.springsource.org/spring-android/docs/1.0.x/reference/… 还有 API 文档:static.springsource.org/spring-android/docs/1.0.x/api/org/…
    • 罗伊,感谢您提供的信息。只有将true 传递给RestTemplate,我才能处理POST。没有那个我遇到了以下异常:org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.util.LinkedMultiValueMap]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2014-02-09
    相关资源
    最近更新 更多