如何从RestTemplate调用URL中提取HTTP状态代码? [英] How to extract HTTP status code from the RestTemplate call to a URL?

查看:889
本文介绍了如何从RestTemplate调用URL中提取HTTP状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RestTemplate 对我们的服务进行HTTP调用,该服务返回一个简单的JSON响应。我根本不需要解析那个JSON。我只需要返回我从该服务中获得的任何内容。

I am using RestTemplate to make an HTTP call to our service which returns a simple JSON response. I don't need to parse that JSON at all. I just need to return whatever I am getting back from that service.

所以我将其映射到 String.class 并以字符串形式返回实际的 JSON响应

So I am mapping that to String.class and returning the actual JSON response as a string.

RestTemplate restTemplate = new RestTemplate();

String response = restTemplate.getForObject(url, String.class);

return response;

现在的问题是 -

I我试图在点击URL后提取 HTTP状态代码。如何从上面的代码中提取HTTP状态代码?我是否需要按照目前的方式对其进行任何更改?

I am trying to extract HTTP Status codes after hitting the URL. How can I extract HTTP Status code from the above code? Do I need to make any change into that in the way I doing it currently?

更新: -

这是我尝试过的,我能够得到回复和状态代码。但我是否总是需要设置 HttpHeaders 实体对象如下所示我在做什么?

This is what I have tried and I am able to get the response back and status code as well. But do I always need to set HttpHeaders and Entity object like below I am doing it?

    RestTemplate restTemplate = new RestTemplate();     

    //and do I need this JSON media type for my use case?
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    //set my entity
    HttpEntity<Object> entity = new HttpEntity<Object>(headers);

    ResponseEntity<String> out = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

    System.out.println(out.getBody());
    System.out.println(out.getStatusCode());

几个问题 - 我需要 MediaType.APPLICATION_JSON 因为我只是调用url来返回响应,它可以返回JSON或XML或简单的字符串。

Couple of question - Do I need to have MediaType.APPLICATION_JSON as I am just making a call to url which returns a response back, it can return either JSON or XML or simple string.

推荐答案

使用 RestTemplate#交换(..) <的code> 方法code> ResponseEntity 。这使您可以访问状态行和标题(显然是身体)。

Use the RestTemplate#exchange(..) methods that return a ResponseEntity. This gives you access to the status line and headers (and the body obviously).

这篇关于如何从RestTemplate调用URL中提取HTTP状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆