问题内容
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":"2022-01-15T08:01:47.498+00:00","status":415,"error":"Unsupported Media Type","trace":"org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=ISO-8859-1' not supported\r\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:206)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:160)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:133)\r\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:179)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:146)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:681)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:764)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.lang.Thread.run(Thread.java:748)\r\n","message":"Content type 'text/plain;charset=ISO-8859-1' not supported","path":"/postContent"}
2.SpringBoot项目后台打印日志
server.port=8081
logging.level.web=DEBUG
2022-01-15 16:01:47.338 INFO 2420 --- [nio-8081-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-01-15 16:01:47.338 INFO 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-01-15 16:01:47.348 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Detected StandardServletMultipartResolver
2022-01-15 16:01:47.348 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Detected AcceptHeaderLocaleResolver
2022-01-15 16:01:47.348 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Detected FixedThemeResolver
2022-01-15 16:01:47.348 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Detected org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@5cd39dc5
2022-01-15 16:01:47.348 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Detected org.springframework.web.servlet.support.SessionFlashMapManager@29562dee
2022-01-15 16:01:47.348 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2022-01-15 16:01:47.348 INFO 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
2022-01-15 16:01:47.368 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : POST "/postContent", parameters={}
2022-01-15 16:01:47.388 DEBUG 2420 --- [nio-8081-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.example.temp.TempApplication#postContent(Map)
2022-01-15 16:01:47.468 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.method.HandlerMethod : Could not resolve parameter [0] in public void com.example.temp.TempApplication.postContent(java.util.Map<java.lang.String, java.lang.Object>): Content type 'text/plain;charset=ISO-8859-1' not supported
2022-01-15 16:01:47.468 WARN 2420 --- [nio-8081-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=ISO-8859-1' not supported]
2022-01-15 16:01:47.478 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Completed 415 UNSUPPORTED_MEDIA_TYPE
2022-01-15 16:01:47.488 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for POST "/error", parameters={}
2022-01-15 16:01:47.488 DEBUG 2420 --- [nio-8081-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2022-01-15 16:01:47.668 DEBUG 2420 --- [nio-8081-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
2022-01-15 16:01:47.668 DEBUG 2420 --- [nio-8081-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{timestamp=Sat Jan 15 16:01:47 CST 2022, status=415, error=Unsupported Media Type, trace=org.springf (truncated)...]
2022-01-15 16:01:47.778 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 415
关键信息
2022-01-15 16:01:47.468 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.method.HandlerMethod : Could not resolve parameter [0] in public void com.example.temp.TempApplication.postContent(java.util.Map<java.lang.String, java.lang.Object>): Content type 'text/plain;charset=ISO-8859-1' not supported
2022-01-15 16:01:47.468 WARN 2420 --- [nio-8081-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=ISO-8859-1' not supported]
2022-01-15 16:01:47.478 DEBUG 2420 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Completed 415 UNSUPPORTED_MEDIA_TYPE
2022-01-15 16:01:47.668 DEBUG 2420 --- [nio-8081-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
2022-01-15 16:01:47.668 DEBUG 2420 --- [nio-8081-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{timestamp=Sat Jan 15 16:01:47 CST 2022, status=415, error=Unsupported Media Type, trace=org.springf (truncated)...]
解决问题
1.查看SpringWeb包里面的MediaType类,是否提供"text/plain;charset=ISO-8859-1",很不幸Spring不提供;可以根据根据实际情况,使用Spring提供的MediaType类型。
public static final String TEXT_PLAIN_VALUE = "text/plain";
2.解决如图