Spring Boot Rest调用中无效的mimetype异常

时间:2018-12-03 09:48:45

标签: spring-boot spring-rest

我对Spring Boot和Rest调用都是陌生的。

我正在尝试使用Rest服务,除URL外,我没有关于Rest API的任何信息。当我从浏览器中访问该URL时,得到的响应为{key:value}。因此,我以为这是JSON响应。

我在Spring Boot中按如下方式使用它 restTemplate.getForObject(url, String.class)

这是给Invalid mime type "content-type: text/plain; charset=ISO-8859-1": Invalid token character ':' in token "content-type: text"

我认为此错误是因为响应内容类型设置为text / plain,但返回的是JSON格式。

编辑:

尝试过这种方法,但是没有用。

HttpHeaders headers = new HttpHeaders();     
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

HttpEntity<String> entity = new HttpEntity<String>("parameters",headers);   
ResponseEntity<String> result = restTemplate.exchange(url,HttpMethod.GET, 
                                             entity, String.class);

如何处理和解决它?

1 个答案:

答案 0 :(得分:1)

您可能想了解REST API需要的请求标头。 Content-Type标头指定您要发送到服务器的请求的媒体类型。因为您只是从服务器获取数据,所以应将Accept标头设置为所需的响应类型,即Accept: application/json

不幸的是,您不能使用getForObject()设置标题。您可以尝试以下方法:

URL url = new URL("Enter the URL of the REST endpoint");
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept", "application/json");
        if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuffer content = new StringBuffer();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
        }