Spring Rest:在服务器端处理POST请求

时间:2016-02-29 00:39:25

标签: android json spring rest spring-io

我根据此链接中的答案提出这个问题

POST request via RestTemplate in JSON

我实际上想从客户端发送JSON并在REST服务器上接收相同的内容。由于客户端部分是在我上面提到的链接中完成的。同样如何在服务器端处理该请求。

客户端:

// create request body
JSONObject request = new JSONObject();
request.put("username", name);
request.put("password", password);

// set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);

// send request and parse result
ResponseEntity<String> loginResponse = restTemplate
  .exchange(urlString, HttpMethod.POST, entity, String.class);
if (loginResponse.getStatusCode() == HttpStatus.OK) {
  JSONObject userJson = new JSONObject(loginResponse.getBody());
} else if (loginResponse.getStatusCode() == HttpStatus.UNAUTHORIZED) {
  // nono... bad credentials
}

服务器

@RequestMapping(method=RequestMethod.POST, value = "/login")
    public ResponseEntity<String> login(@RequestBody HttpEntity<String> entity) {
        JSONObject jsonObject = new JSONObject(entity.getBody());
        String username = jsonObject.getString("username");
        return new ResponseEntity<>(username, HttpStatus.OK);
    }

这在客户端给出了400个错误的请求错误。希望能找到一些关于如何在服务器端处理这个问题的线索。

2 个答案:

答案 0 :(得分:1)

不应在您的服务器方法中使用HTTPEntity。而是使用从客户端传递给HTTPEntity的参数。在你的情况下,它必须是String,因为你从客户端传递字符串。下面的代码应该适合你。

@RequestMapping(method=RequestMethod.POST, value = "/login")
public ResponseEntity<String> login(@RequestBody String jsonStr) {
    System.out.println("jsonStr  " + jsonStr);
    JSONObject jsonObject = new JSONObject(jsonStr);
    String username = jsonObject.getString("username");
    return new ResponseEntity<String>(username, HttpStatus.OK);
}  

我的建议是创建bean类并在服务器和客户端中使用它,而不是将其转换为String。它将提高代码的可读性。

答案 1 :(得分:0)

使用Spring RestTemplate时,我通常更喜欢直接交换对象。例如:

  

第1步:声明并定义数据持有者类

class User {
  private String username;
  private String password;

  ... accessor methods, constructors, etc. ...
}
  

第2步:使用RestTemplate

将此类的对象发送到服务器
... You have a RestTemplate instance to send data to the server ...

// You have an object to send to the server, such as:
User user = new User("user", "secret");

// Set HTTP headers for an error-free exchange with the server.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

// Generate an HTTP request payload.
HttpEntity<User> request = new HttpEntity<User>(user, headers);

// Send the payload to the server.
restTemplate.exchange("[url]", [HttpMethod], request, User.class);
  

第3步:在服务器上配置ContentNegotiatingViewResolver

在Spring XML或Java配置中声明类型为ContentNegotiatingViewResolver的bean。这将有助于服务器自动将HTTP请求与bean对象绑定。

  

第4步:在服务器上接收请求

@RestController
@RequestMapping("/user")
class UserAPI {
  @RequestMapping(method = RequestMethod.POST)
  @ResponseBody
  public User create(User user) {
    // Process the user.

    // Possibly return the same user, although anything can be returned.
    return user;
  }
}

ContentNegotiatingViewResolver可确保传入请求转换为User实例,而无需任何其他干预。

  

第5步:在客户端上接收回复

// Receive the response.
HttpEntity<User> response = restTemplate.exchange("[url]", [HttpMethod], request, User.class);

// Unwrap the object from the response.
user = response.getBody();

您会注意到客户端和服务器都使用相同的bean类(User)。这保持同步,因为bean结构中的任何重大更改都会立即导致其中一个或两个的编译失败,从而需要在部署代码之前进行修复。