【发布时间】:2019-03-20 16:41:51
【问题描述】:
Spring Boot RestTemplate 交换有问题。
我有以下代码:
@RequestMapping(path = "/add")
public @ResponseBody String addFromTo () {
String apikey = "";
String baseurl = "http://demowebshop.webshop8.dk/admin/WEBAPI/v2/orders?start=2018-10-05T20%3A49%3A41.745Z&end=2018-10-15T20%3A49%3A41.745Z&api_key=" + apikey;
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setBasicAuth("", apikey);
HttpEntity<String> request = new HttpEntity<String>(" ", headers);
ResponseEntity<OrderResponse> response = restTemplate.exchange(baseurl, HttpMethod.GET, request, OrderResponse.class);
return "Some text.";
}
我想要的是相当于:
curl -X GET --header 'Accept: application/json' --header 'Authorization: Basic {encodedapikey}' 'http://demowebshop.webshop8.dk/admin/WEBAPI/v2/orders?start=2018-10-06T06%3A43%3A40.926Z&end=2018-10-16T06%3A43%3A40.926Z&api_key={apikey}'
我尝试使用具有完全相同 URL 的 Postman,并使用 apikey 和“Accept: application/json”标头添加基本身份验证,效果很好,但是当我运行此代码时,我得到了错误留言:
There was an unexpected error (type=Internal Server Error, status=500).
400 Bad Request
编辑: Pastebin 链接到程序抛出的异常: https://pastebin.com/jdYJ2nv7
【问题讨论】:
-
是
setBasicAuth应该是'' "? -
应该没有用户名。如果您尝试访问 URL,它也可以在浏览器中使用,它会询问用户名和密码,我将用户名留空并使用 apikey 作为密码。
-
似乎缺少一些东西..如果你看到代码 String apikey = "";但是你在哪里设置这个字符串值..它总是传递为“''。
-
apikey 字段通常不会丢失,我只是没有将其包含在问题中。
-
您发布的内容不同...参数再次编码,导致
%3A再次编码为其他内容。除此之外,您没有像使用 CURL 那样提供encodedapikey。所以你没有做同样的事情,但期待同样的结果......
标签: java spring rest http spring-boot