Spring RESTful应用程序中的HTTP POST请求

时间:2017-08-02 07:06:11

标签: java json rest spring-mvc spring-boot

我使用Spring RESTful应用并尝试执行POST请求。它会发布数据,但是,当我尝试GET时,数据格式似乎格式不正确。该方法在下面提供,

@RestController
@RequestMapping("/rest")
@Produces({"text/plain", "application/xml", "application/json"})
public class WalletRestController {

    @Autowired
    private WalletService walletService;

@PostMapping("/generateAddress")
    public ResponseEntity<Void> generateAddress(@RequestBody String walletName,
                                                UriComponentsBuilder uriComponentsBuilder) {

        System.out.println("Creating wallet with name = " + walletName);

        if (walletName == null) {
            return new ResponseEntity<Void>(HttpStatus.NOT_ACCEPTABLE);
        }

        walletService.generateAddress(walletName);

        HttpHeaders httpHeaders = new HttpHeaders();
//      httpHeaders.setLocation(uriComponentsBuilder.path("/wallets/{id}").buildAndExpand(walletInfo.getId()).toUri());            

return new ResponseEntity<Void>(httpHeaders, HttpStatus.CREATED);
        }

    }

POST中的Curl请求,

curl -H "Content-Type: application/json" -X POST -d '{"name":"mikiii"}' http://localhost:8080/rest/generateAddress

我使用GET

获取数据
[
  // more data  
  {
    "id": 16,
    "name": "{\"name\":\"mikiii\"}",
    "address": "mvmHyU1k6qkoUEpM9CQg4kKTzQ5si3oR1e"
  }
]

如果我只使用String

curl -H "Content-Type: application/json" -X POST -d '"muuul"' http://localhost:8080/rest/generateAddress

我把它作为

回来了
[
// ........., 
{
    "id": 17,
    "name": "\"muuul\"",
    "address": "mr9ww7vCUzvXFJ6LDAz6YHnHPsd9kgYfox"
  }
]

这是generateAddress方法(I have the same name, should have changed)的内部实现,创建一个新的WalletInfo实体并且当前返回void

   @Override
    public synchronized void generateAddress(final String walletName) {

        WalletInfo walletInfo = walletInfoDao.getByName(walletName);

        // generate wallet, if the wallet is not
        // generated previously
        if (walletInfo == null) {

            if (genWalletMap.get(walletName) == null) {
                final WalletManager walletManager = WalletManager.setupWallet(walletName);
                walletManager.addWalletSetupCompletedListener((wallet) -> {
                    Address address = wallet.currentReceiveAddress();
                    WalletInfo newWallet = createWalletInfo(walletName, address.toString());

                    walletMangersMap.put(newWallet.getId(), walletManager);
                    genWalletMap.remove(walletName);
                });
                genWalletMap.put(walletName, walletManager);

                // return walletInfo;
            }
        }

        // return null;
    }

目前,generateAddress会返回void。之前,我尝试从方法返回WalletInfo并使用代码设置位置,      httpHeaders.setLocation(uriComponentsBuilder.path("/wallets/{id}").buildAndExpand(walletInfo.getId()).toUri());

我收到错误,但这似乎无效。如有必要,我可以提供该错误堆栈,但是,现在我再次从当前代码中的方法返回void

RESTful方法级别,我尝试使用@PathVariable("name") String walletNameString walletName。显而易见,这并没有帮助 并提供错误。

UPDATE

下面提供了GET请求的Curl方法处理程序,

// curl -G http://localhost:8080/rest/wallets | json

@RequestMapping(value = "/wallets", method = RequestMethod.GET)
public ResponseEntity<List<WalletInfo>> getAllWalletInfo() {

     List<WalletInfo> walletInfos = walletService.getAllWallets();

    if (Objects.isNull(walletInfos)) {
       return new ResponseEntity<List<WalletInfo>>(HttpStatus.NO_CONTENT);
     }
     return new ResponseEntity<List<WalletInfo>>(walletInfos, 
 HttpStatus.OK);

}

// curl -G http://localhost:8080/rest/wallets/1 | json

@RequestMapping(value = "/wallets/{id}", method = RequestMethod.GET)
public ResponseEntity<WalletInfo> getWalletById(@PathVariable("id") long id) {

    System.out.println("Get wallet info with Id = " + id);

    WalletInfo walletInfo = walletService.getWalletInfo(id);

    if (walletInfo == null) {
        return new ResponseEntity<WalletInfo>(HttpStatus.NOT_FOUND);
    }

    return new ResponseEntity<WalletInfo>(walletInfo, HttpStatus.OK);
}

如何获取干净String中的地址"name": "testuser",并提出正确的POST请求?

1 个答案:

答案 0 :(得分:1)

目前,您正在将WalletInfo作为响应实体getWalletById()返回。

return new ResponseEntity<WalletInfo>(walletInfo, HttpStatus.OK);

因此,这个WalletInfo将由jackson mapper转换,WalletInfo中的相应字段将作为json对象返回。我猜你有WalletInfo类的id,姓名和地址字段。 如果您只想返回这些字段的子集,如名称和地址,则创建一个包装类,如

public class WalletInfoWrapper {
   String name;
   String address;
  .. //gettter , setter
}

从您的处理程序返回此类的对象,因此您的新方法get方法处理程序将类似于

@RequestMapping(value = "/wallets/{id}", method = RequestMethod.GET)
public ResponseEntity<WalletInfoWrapper > getWalletById(@PathVariable("id") long id) {

    System.out.println("Get wallet info with Id = " + id);

    WalletInfo walletInfo = walletService.getWalletInfo(id);

    if (walletInfo == null) {
        return new ResponseEntity<WalletInfo>(HttpStatus.NOT_FOUND);
    }
   WalletInfoWrapper walletInfoWrapper = new WalletInfoWrapper ();
walletInfoWrapper.setName(walletInfo.getName());
walletInfoWrapper.setAddress(walletInfo.getAddress());
    return new ResponseEntity<WalletInfoWrapper >(walletInfoWrapper , HttpStatus.OK);
}

如果您只想要地址,那么您的包装器只能包含地址字段。 另外,如果你在每个双引号之前对“\”感到困扰,那是因为你将其余调用的输出重定向到json实用程序

curl -G http://localhost:8080/rest/wallets/1 | json

,你可以通过

看到普通输出
curl -G http://localhost:8080/rest/wallets/1