GVKun编程网logo

如何在Spring RestTemplate请求上设置“ Accept:”标头?(spring的resttemplate)

18

关于如何在SpringRestTemplate请求上设置“Accept:”标头?和spring的resttemplate的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于java–如何使Sp

关于如何在Spring RestTemplate请求上设置“ Accept:”标头?spring的resttemplate的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于java – 如何使Spring RestTemplate PATCH请求、java – 如何删除Spring的RestTemplate添加的某些HTTP头?、java – 如何在Spring RestTemplate中使用JAXB注释?、java – 测量Spring RestTemplate HTTP请求时间等相关知识的信息别忘了在本站进行查找喔。

本文目录一览:

如何在Spring RestTemplate请求上设置“ Accept:”标头?(spring的resttemplate)

如何在Spring RestTemplate请求上设置“ Accept:”标头?(spring的resttemplate)

我想Accept:在使用Spring的请求中设置的值RestTemplate

这是我的Spring请求处理代码

@RequestMapping(    value= "/uom_matrix_save_or_edit",     method = RequestMethod.POST,    produces="application/json")public @ResponseBody ModelMap uomMatrixSaveOrEdit(    ModelMap model,    @RequestParam("parentId") String parentId){    model.addAttribute("attributeValues",parentId);    return model;}

这是我的Java REST客户端:

public void post(){    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();    params.add("parentId", "parentId");    String result = rest.postForObject( url, params, String.class) ;    System.out.println(result);}

这对我有用;我从服务器端获取了JSON字符串。

我的问题是:当我使用RestTemplate时,如何指定Accept:标头(例如application/json,application/xml...)和请求方法(例如,…)?GETPOST

答案1

小编典典

我建议使用exchange可以接受的方法之一,也可以HttpEntity为其设置HttpHeaders。(你也可以指定要使用的HTTP方法。)

例如,

RestTemplate restTemplate = new RestTemplate();HttpHeaders headers = new HttpHeaders();headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));HttpEntity<String> entity = new HttpEntity<>("body", headers);restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

我喜欢这种解决方案,因为它是强类型的。exchange期望一个HttpEntity

不过,你也可以将其HttpEntity作为request参数传递给postForObject

HttpEntity<String> entity = new HttpEntity<>("body", headers);restTemplate.postForObject(url, entity, String.class); 

RestTemplate#postForObjectJavadoc中提到了这一点。

该request参数可以是a HttpEntity,以便向请求中添加其他HTTP标头。

java – 如何使Spring RestTemplate PATCH请求

java – 如何使Spring RestTemplate PATCH请求

参见英文答案 > RestTemplate PATCH request                                    3个
我需要使用HTTP PATCH动词使用Spring的RestTemplate调用服务.从我读到的,我需要使用execute()或exchange()方法,但我不知道如何使用它.服务调用返回HTTP 200 OK状态,以及我不是特别感兴趣的JSON对象.

任何帮助将不胜感激.

最佳答案
可以使用PATCH谓词,但必须使用带有exchange()的RestTemplate类的Apache HTTP客户端库.您可能不需要映射器部分.下面的EmailPatch类仅包含我们要在请求中更新的字段.

  ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNowN_PROPERTIES,false);
    mapper.registerModule(new Jackson2HalModule());

    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json"));
    converter.setobjectMapper(mapper);

    HttpClient httpClient = HttpClients.createDefault();
    RestTemplate restTemplate = new RestTemplate(Collections.etonList(converter));
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)); 
    EmailPatch patch = new EmailPatch();
    patch.setStatus(1);
    ResponseEntityhttpentity

java – 如何删除Spring的RestTemplate添加的某些HTTP头?

java – 如何删除Spring的RestTemplate添加的某些HTTP头?

我遇到了远程服务的问题我无法控制对使用Spring的RestTemplate发送的请求的HTTP 400响应.使用curl发送的请求会被接受,因此我将它们与通过RestTemplate发送的请求进行了比较.特别是,Spring请求具有标题Connection,Content-Type和Content-Length,而curl请求则没有.如何配置Spring不添加它们?

最佳答案
实际上这可能不是问题所在.我的猜测是你没有指定正确的消息转换器.但这是一种删除标题的技术,以便您可以确认:

1.创建自定义ClientHttpRequestInterceptor实现:

public class CustomHttpRequestInterceptor implements ClientHttpRequestInterceptor
{

   @Override
   public ClientHttpResponse intercept(HttpRequest request,byte[] body,ClientHttpRequestExecution execution) throws IOException
   {
        HttpHeaders headers = request.getHeaders();
        headers.remove(HttpHeaders.CONNECTION);
        headers.remove(HttpHeaders.CONTENT_TYPE);
        headers.remove(HttpHeaders.CONTENT_LENGTH);

        return execution.execute(request,body);
    }

}

2.然后将其添加到RestTemplate的拦截器链:

@Bean
public RestTemplate restTemplate()
{

   RestTemplate restTemplate = new RestTemplate();
   restTemplate.setInterceptors(Arrays.asList(new CustomHttpRequestInterceptor(),new LoggingRequestInterceptor()));

   return restTemplate;
}

java – 如何在Spring RestTemplate中使用JAXB注释?

java – 如何在Spring RestTemplate中使用JAXB注释?

我正在尝试使用Spring的RestTemplate自动反序列化XML格式的响应.我正在使用Jackson的jackson-dataformat-xml模块,Spring Boot设置为自动配置.我想在我要反序列化的类中使用JAXB注释,但它似乎不起作用.以下是我希望该类看起来像的示例:

@XmlRootElement(name="Book")
public class Book {

    @XmlElement(name="Title")
    private String title;
    @XmlElement(name="Author")
    private String author;

}

这基于以下XML示例:

但是,如上所述注释类,字段始终设置为null.我做了一些实验,发现如果我使用Jackson的@JsonProperty注释子元素,反序列化就有效:

@XmlRootElement(name="Book")
public class Book {

    @JsonProperty("Title")
    private String title;
    @JsonProperty("Author")
    private String author;

}

它有效,但不知怎的,我觉得它有点尴尬.有没有办法让JAXB注释像我的第一个例子一样工作?

Jackson提供了jackson-module-jaxb-annotations模块用于XML数据绑定以使用JAXB注释.但是,我不确定如何设置RestTemplate使用的ObjectMapper来使用此模块.

最佳答案
为了解决这个问题,我需要向添加到Spring的RestTemplate的转换器使用的每个ObjectMapper注册一个JaxbAnnotationModule实例.该课程包含在Jackson的jackson-module-jaxb-annotations模块中,我通过Gradle添加到我的构建中.

随着依赖项添加到我的项目中,我接下来要做的是配置我的应用程序使用的RestTemplate. Spring自动配置的MappingJackson2XmlHttpMessageConverters正在使用ObjectMapper实例.我必须将JaxbAnnotationModule实例注册到每个转换器中使用的每个ObjectMapper,因此第一个任务是使用以下命令查找所有MappingJackson2XmlHttpMessageConverters:

//create module
JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();

restTemplate.getMessageConverters().stream().filter(converter -> {
    return converter instanceof MappingJackson2XmlHttpMessageConverter;
})

一旦我拥有了所有相关的转换器,我就将模块注册到它们的每个ObjectMappers:

forEach(converter -> {
    ((MappingJackson2XmlHttpMessageConverter) converter)
            .getobjectMapper()
            .register(jaxbAnnotationModule);
});

java – 测量Spring RestTemplate HTTP请求时间

java – 测量Spring RestTemplate HTTP请求时间

我想测量RestTemplate.getForObject调用的HTTP GET请求的时间,而不需要解析响应所需的时间.所以只是远程HTTP调用所需的时间.我已经尝试过设置ClientHttpRequestInterceptor,但我不认为这是正确的方法,因为时间似乎是错误的:

public class PerfRequestSyncInterceptor implements ClientHttpRequestInterceptor {
private Logger log = Logger.getLogger(this.getClass());

@Override
  public ClientHttpResponse intercept(HttpRequest request,byte[] body,ClientHttpRequestExecution execution) throws IOException {

    long start = System.nanoTime();
    ClientHttpResponse resp = execution.execute(request,body);

    log.debug("remote request time: "
            + ((System.nanoTime() - start) * Math.pow(10,-9)));
    return resp;
  }
}

呼叫:

RestTemplate rest = new RestTemplate();
List

如何衡量RestTemplate HTTP请求的时间?

最佳答案
您可以使用AOP和Spring内置的PerformanceMonitorInterceptor.您需要正确定义要拦截哪种calss的方法,然后才能进行测量.您可以配置如下:

spring-beans-2.0.xsd
        http://www.springframework.org/schema/aop   
        http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
    fig>
            pointcut"
                   expression="execution(* java.net.HttpURLConnection.connect(..))"/>




                pointcut" 
            advice-ref="springMonitoringAspectInterceptor"/>      
    fig>

关于如何在Spring RestTemplate请求上设置“ Accept:”标头?spring的resttemplate的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于java – 如何使Spring RestTemplate PATCH请求、java – 如何删除Spring的RestTemplate添加的某些HTTP头?、java – 如何在Spring RestTemplate中使用JAXB注释?、java – 测量Spring RestTemplate HTTP请求时间的相关信息,请在本站寻找。

本文标签: