简体   繁体   English

Spring RESTful应用中的HTTP POST请求

[英]HTTP POST request in the Spring RESTful app

I work with a Spring RESTful app and tries to do a POST request. 我使用Spring RESTful应用程序,尝试执行POST请求。 It posts the data, but, when I tried to GET it back, the data format seems not in the correct format. 它职位数据,但是,当我试图GET回,数据格式好像不是正确的格式。 The method is provided below, 下面提供了该方法,

@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);
        }

    }

The POST request in Curl , CurlPOST请求,

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

I get the data using the GET , 我使用GET获取数据,

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

If I use only a String , 如果我只使用String

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

I get it back as 我把它拿回来

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

This is the inner implementation of the generateAddress method (I have the same name, should have changed) create a new WalletInfo entity and currently returns void , 这是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;
    }

Currently, the generateAddress returns void . 当前, generateAddress返回void Earlier, I tried to return the WalletInfo from the method and set the location using the code, httpHeaders.setLocation(uriComponentsBuilder.path("/wallets/{id}").buildAndExpand(walletInfo.getId()).toUri()); 之前,我尝试从该方法返回WalletInfo并使用代码httpHeaders.setLocation(uriComponentsBuilder.path("/wallets/{id}").buildAndExpand(walletInfo.getId()).toUri());

I get an error and this seems not working. 我收到一个错误,这似乎不起作用。 I can provide that error stack if necessary, but, now again I return the void from the method in the current code. 如果需要,我可以提供该错误堆栈,但是,现在我再次在当前代码中从该方法返回void

In the RESTful method level, I have tried with @PathVariable("name") String walletName and String walletName . RESTful方法级别,我尝试使用@PathVariable("name") String walletNameString walletName Obvously, this didn't help out and provided errors. 显然,这无济于事,并提供了错误。

UPDATE

The GET method handlers with the Curl request are provided below, 下面提供了带有Curl请求的GET方法处理程序,

// 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);
}

How to get the address in the clean String like "name": "testuser" and have a proper POST request? 如何在干净的String获取地址,例如"name": "testuser"并具有正确的POST请求?

Currently you are returning WalletInfo as a response entity getWalletById (). 当前,您将WalletInfo作为响应实体getWalletById()返回。

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

So this WalletInfo will be converted by jackson mapper and the corresponding fields in WalletInfo will be returned as a json object. 因此,此WalletInfo将由jackson mapper转换,并且WalletInfo中的相应字段将作为json对象返回。 I am guessing you have id, name and address fields in you WalletInfo class. 我猜您在WalletInfo类中具有ID,名称和地址字段。 If you only want to return a subset of these fields like , name and address, then create a wrapper class like 如果您只想返回这些字段的子集,例如,name和address,则创建一个包装类,例如

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

And return the object of this class from your handler , so your new code of get method handler will look like 并从处理程序中返回此类的对象,因此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);
}

If you just want the address then your wrapper can have only address field. 如果只需要地址,则包装器只能有一个地址字段。 Plus if you are bothered about the "\\" before each double quotes, that is because you are redirecting the output from the rest call to a json utility 另外,如果您对每个双引号之前的“ \\”感到不安,那是因为您要将输出从rest调用重定向到json实用程序

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

, You can see the plain output by just ,您可以通过

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM