spring的RestTemplate添加请求头 get请求

直接上代码

public  static Object get(String url, Map map){
        HttpHeaders headers = new HttpHeaders();
        headers.set("groupId", TransactionManage.getCurrent());
        headers.set("contentType", "application/json;charset=UTF-8");
        headers.set("transactionCount", String.valueOf(TransactionManage.getTransactionCount()));
        HttpEntity> request = new HttpEntity(null, headers);

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        for (Map.Entry param : map.entrySet()) {
            builder.queryParam(param.getKey(),param.getValue());
        }
        return restTemplate.exchange(builder.build().toString(), HttpMethod.GET, request, Object.class).getBody();
    }

注:其中map为get请求参数

其中有个问题出现:

nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'SUCCESS'

出错代码:

@RestController
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    @GetMapping("/decreaseStock")
    public String createOrder(Integer goodsId, Integer count) {
        try {
            goodsService.decreaseStock(goodsId, count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString("success");
    }
}

解决:

将返回参数使用json字符串,原因就不深究了,就是json转化异常,序列化要求序列化和反序列化使用同一个协议

@RestController
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    @GetMapping("/decreaseStock")
    public String createOrder(Integer goodsId, Integer count) {
        try {
            goodsService.decreaseStock(goodsId, count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString("SUCCESS");
    }
}

 

你可能感兴趣的:(spring,springboot)