使用RestTemplate发送POST请求时,我一直收到400 BAD请求。 我正在发送一个对象列表,为此我创建了一个类AllCars女巫作为我的班级汽车的字段列表:
public class AllCars {
private List<Cars> listcars;
public AllCars() {
}
public AllCars(List<Cars> listcars) {
this.listcars = listcars;
}
public List<Cars> getListcars() {
return listcars;
}
public void setListcars(List<Cars> listcars) {
this.listcars = listcars;
}
}
汽车类
public class Cars {
private Long id;
private long speed;
private String color;
public Cars() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public long getSpeed() {
return speed;
}
public void setSpeed(long speed) {
this.speed = speed;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
这是我的客户端代码:
private class SendData extends AsyncTask<AllCars, Object, AllCars> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getContext(), "Downloading", "Downloading..Please Wait", true);
}
@Override
protected AllCars doInBackground(AllCars... params) {
try {
// urls
final String urlCars = "http://myurl/addCars";
publishProgress(0);
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson and String message converters
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
AllCars result = restTemplate.postForObject(urlAllCars, params[0], AllCars.class);
return result;
} catch (Exception e) {
Log.e("mainactivity", e.getMessage(), e);
}
return null;
}
@Override
protected void onPostExecute(AllCars ob) {
if(ob instanceof AllCars)
Log.d("AllCars", "success " );
else
Log.d("No Result ", "");
progressDialog.cancel();
}
}
这是我的服务器端代码:
@Requesrmaping (vlaue = "/addCars", method=RequestMethod.POST)
public ResponseEntity<AllCars>addCars(@RequestBody AllCars allcars){
List<Cars> listcar= allcars.getListcars();
return new ResponsEntity<AllCars>(allcars,HttpStatus.ok)
}
这个代码适用于listcare有一个对象但是当它有多个对象时它没有工作可以帮助我