我正在使用 spring android 框架通过 Http POST 检索 json 数据。但是在使用服务时,服务器端收到的参数为空。
以下是android代码:
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"}
谢谢!
最佳答案
我自己解决了这个问题。 需要输入以下代码
RestTemplate restTemplate = new RestTemplate(true);
POST 请求需要 True。 默认情况下它是 false,即针对 GET 请求。 甚至在Spring Android Reference link上也没有提到这一点。
关于android - 使用 Spring Android 框架通过 HTTP POST 检索 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14956898/