HttpMediaTypeNotSupportedException: Content type ‘text/plain;charset=ISO-8859-1‘ not supported

当使用httpclient调用本地或其他系统接口时,遇到HttpMediaTypeNotSupportedException,错误内容为'text/plain;charset=ISO-8859-1'不被支持。该问题源于SpringBoot项目不支持此内容类型。解决方案包括检查SpringWeb的MediaType类,并根据实际需求使用Spring提供的MediaType。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题内容

httpclient调用本地其他服务,或者第三方系统接口,出现如下图问题:

准备内容

httpclient的maven依赖

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.10</version>
    </dependency>

新建项目

1.新建一个SpringBoot项目

package com.example.temp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Description;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@SpringBootApplication
public class TempApplication {

    @Description("模拟本地其他服务接口,或者第三方接口")
    @PostMapping(path = "/postContent")
    public void postContent(@RequestBody Map<String,Object> mapContent) {
        System.out.println(mapContent);
    }

    public static void main(String[] args) {
        SpringApplication.run(TempApplication.class, args);
    }

}

2.新建一个客户端调用接口

package org.example;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientDemo {
    public static void main(String[] args) {

        try {
            String result = sendPOST();
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static String sendPOST() throws IOException {

        String result = "";
        HttpPost post = new HttpPost("http://localhost:8081/postContent");

        // json content
        String json = "{\n" +
                "    \"teslaKey\":\"teslaValue\",\n" +
                "    \"requestKey\":\"{\\\"customKey\\\":\\\"customValue\\\"}\"\n" +
                "}";

        System.out.println(json);

        // send a JSON data
        post.setEntity(new StringEntity(json));

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(post)) {

            result = EntityUtils.toString(response.getEntity());
        }

        return result;
    }

}

运行结果

1.客户端调用SpringBoot项目接口,打印问题

{
    "teslaKey":"teslaValue",
    "requestKey":"{\"customKey\":\"customValue\"}"
}
{"timestamp":"2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值