2

我正在使用 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"}

谢谢!

4

1 回答 1

2

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

RestTemplate restTemplate = new RestTemplate(true);

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

于 2013-02-21T07:35:02.740 回答