Java 将我的自定义 http 标头添加到 Spring RestTemplate 请求/扩展 RestTemplate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32623407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:51:31  来源:igfitidea点击:

Add my custom http header to Spring RestTemplate request / extend RestTemplate

javaspringrestcustom-headers

提问by user1209216

My current code:

我目前的代码:

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingHymanson2HttpMessageConverter());
Mall[] malls = restTemplate.getForObject(url, Mall[].class);

I need to add some custom headers for my request, in form:

我需要为我的请求添加一些自定义标头,格式为:

X-TP-DeviceID : <GUID>

What is the simplest way to do that in my case? Is there any way to add custom headers definition to my restTemplateobject before I send the request to server?

在我的情况下,最简单的方法是什么?restTemplate在将请求发送到服务器之前,有什么方法可以将自定义标头定义添加到我的对象中?

[edit]

[编辑]

Is it correct?

这是正确的吗?

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingHymanson2HttpMessageConverter());

HttpHeaders headers = new HttpHeaders();
headers.set("X-TP-DeviceID", "1234567890");
HttpEntity entity = new HttpEntity(headers);

HttpEntity<Mall[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, Mall[].class);

Mall[] malls = response.getBody();

[added]

[添加]

So, I managed to get it working. However, I'm not fully satisfied with that. In my case I will need to provide the same custom headers for all the calls I make.

所以,我设法让它工作。但是,我对此并不完全满意。在我的情况下,我需要为我所做的所有调用提供相同的自定义标头。

So, my next question is - Is it possible to set my custom headers to be added automatically on each web-servicecall, for example, by extending RestTemplateclass and putting all custom headers there? Then, all I would be needing to do would be to simply use my custom extended RestTemplateinstead of the stock one, and all my custom headers will be present there by default.

所以,我的下一个问题是 - 是否可以将我的自定义标题设置为在每次web-service调用时自动添加,例如,通过扩展RestTemplate类并将所有自定义标题放在那里?然后,我需要做的就是简单地使用我的自定义扩展RestTemplate而不是股票,默认情况下我的所有自定义标题都将出现在那里。

回答by kswaughs

You can pass custom http headers with RestTemplate exchange method as below.

您可以使用 RestTemplate 交换方法传递自定义 http 标头,如下所示。

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");

HttpEntity<RestRequest> entityReq = new HttpEntity<RestRequest>(request, headers);

RestTemplate template = new RestTemplate();

ResponseEntity<RestResponse> respEntity = template
    .exchange("RestSvcUrl", HttpMethod.POST, entityReq, RestResponse.class);

EDIT : Below is the updated code. This link has several ways of calling rest service with examples

编辑:以下是更新后的代码。这个链接有几种通过例子调用休息服务的方法

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");

HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

ResponseEntity<Mall[]> respEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Mall[].class);

Mall[] resp = respEntity.getBody();

回答by Sean Gildea

Add a "User-Agent" header to your request.

向您的请求添加“User-Agent”标头。

Some servers attempt to block spidering programs and scrapers from accessing their server because, in earlier days, requests did not send a user agent header.

一些服务器试图阻止蜘蛛程序和抓取程序访问他们的服务器,因为在早期,请求没有发送用户代理标头。

You can either try to set a custom user agent value or use some value that identifies a Browser like "Mozilla/5.0 Firefox/26.0"

您可以尝试设置自定义用户代理值或使用一些标识浏览器的值,例如“Mozilla/5.0 Firefox/26.0”

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();

headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("user-agent", "Mozilla/5.0 Firefox/26.0");
headers.set("user-key", "your-password-123"); // optional - in case you auth in headers
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Game[]> respEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Game[].class);

logger.info(respEntity.toString());

回答by k_o_

If the goal is to have a reusable RestTemplate which is in general useful for attaching the same header to a series of similar request a org.springframework.boot.web.client.RestTemplateCustomizerparameter can be used with a RestTemplateBuilder:

如果目标是拥有一个可重用的 RestTemplate,它通常可用于将相同的标头附加到一系列类似的请求中,则org.springframework.boot.web.client.RestTemplateCustomizer可以将参数与 一起使用RestTemplateBuilder

 String accessToken= "<the oauth 2 token>";
 RestTemplate restTemplate = new RestTemplateBuilder(rt-> rt.getInterceptors().add((request, body, execution) -> {
        request.getHeaders().add("Authorization", "Bearer "+accessToken);
        return execution.execute(request, body);
    })).build();