从浏览器工作获取请求但使用RestTemplate类我对同一请求获得了404响应

时间:2016-10-13 14:48:36

标签: spring spring-boot

如果我从浏览器发送以下get请求,我可以轻松获得预期的JSON响应:

http://www.bookandwalk.hu/api/AdminTransactionList?password=XXX&begindate=2016-04-30&enddate=2016-10-12&corpusid=HUBW

我尝试使用SPRING BOOT 1.4创建一个小型演示应用程序,以查看休息调用在Spring中的工作原理。 所以我创建了一个表示我的域对象的POJO,并通过以下方法调用请求了域对象列表:

String startDate=new SimpleDateFormat("yyyy-MM-dd").format(start.getTime());
String endDate=new SimpleDateFormat("yyyy-MM-dd").format(end.getTime());
UriComponents uri=UriComponentsBuilder.newInstance().scheme("http").host("www.bookandwalk.hu").path("/api/AdminTransactionList").queryParam("password","xxx").queryParam("begindate",startDate).queryParam("enddate",endDate).queryParam("corpusid","HUBW").build().encode();

    LOG.log(Level.INFO,"{0} were called as a rest call",uri.toString());

    ResponseEntity<List<BandWTransaction>> transResponse =
            restTemplate.exchange(uri.toString(),
                        HttpMethod.GET, null, new ParameterizedTypeReference<List<BandWTransaction>>() {
                });

    List<BandWTransaction> transactions = transResponse.getBody();

我遇到以下异常:

org.springframework.web.client.HttpClientErrorException: 404 Not Found

当我记录了uri.toString()时,我将其复制到我的浏览器中以仔细检查我的uri中是否存在任何拼写错误,但它没有任何失败。 有人知道为什么相同的字符串可以从浏览器中运行而不能从代码中运行吗?

1 个答案:

答案 0 :(得分:0)

您似乎应该在此webapp的请求中指定用户代理标头。使用HttpEntity对象设置此标头。

final HttpHeaders headers = new HttpHeaders();
headers.set("User-Agent", "eltabo");

final HttpEntity<String> entity = new HttpEntity<String>(headers);

ResponseEntity<List<BandWTransaction>> transResponse =
        restTemplate.exchange(uri.toString(),
                HttpMethod.GET, entity, 
                new ParameterizedTypeReference<List<BandWTransaction>>() {});

希望它有所帮助。