“找不到Content-Type”:使用RESTTemplate POST到HTTP端点时出现问题

时间:2017-11-02 09:42:35

标签: http resttemplate httpentity

我正在尝试使用RESTTemplate将XML正文POST到HTTP端点,但是引发了以下异常 - “org.springframework.web.client.RestClientException:无法提取响应:找不到Content-Type”。

我已经检查过并且XML文件正在成功发布到端点,但我无法解决此异常 - 显然我做错了。我想我可能需要使用HTTP Mapping Converter,但我不知道如何实现它。

def post(String jenkinsURL,String username,String apiCredentials,String jobName){

    RestTemplate rest = new RestTemplate()
    String url = "http://$jenkinsURL//createItem?name=$jobName"
    def jenkinsConfigPath = "src/main/resources/JenkinsConfig.xml"
    def encoding = Base64.getEncoder().encodeToString((username + ":" + apiCredentials).getBytes())
    String xmlConfigFile = jenkinsConfigReader.read(jenkinsConfigPath)

    HttpHeaders headers = new HttpHeaders()
    headers.setContentType(MediaType.APPLICATION_XML)
    headers.add("Authorization", "Basic " + encoding)

    HttpEntity<String> entity = new HttpEntity<String>(xmlConfigFile, headers)

    rest.exchange(url, HttpMethod.POST, entity, String.class)

1 个答案:

答案 0 :(得分:0)

在Java中,我编写了一个类似的过滤器:

@Provider
public class CorsFilter implements ContainerResponseFilter
{
    @Override
    public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
            throws IOException
    {
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        responseContext.getHeaders().add(
                "Access-Control-Allow-Headers",
                "origin, content-type, accept, authorization, X-Requested-With");
        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "false");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        if(requestContext.getMethod().equals("OPTIONS"))
        {
            responseContext.setStatus(200);
        }
    }

}

提供程序只是扩展和自定义JAX-RS运行时的一种方式。也许这也是一种解决问题的方法。