Spring 启动 rest 调用中的无效 mimetype 异常

Invalid mimetype exception in Spring boot rest call

我对 Spring 引导和休息调用都不熟悉。

我正在尝试使用休息服务,但我没有关于休息的任何信息 API 除了 URL。当我从浏览器中点击 URL 时,我得到的响应是 {key:value}。所以,我假设这是一个 JSON 响应。

我在 spring 引导中使用它,如下所示 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);

如何处理和解决?

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

遗憾的是,您无法使用 getForObject() 设置 headers。你可以试试这个:

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();
        }