2424
2525import jakarta .servlet .AsyncContext ;
2626import jakarta .servlet .ServletResponse ;
27+ import org .jetbrains .annotations .NotNull ;
2728import org .springframework .beans .factory .annotation .Autowired ;
2829import org .springframework .http .*;
2930import org .springframework .http .client .HttpComponentsClientHttpRequestFactory ;
3738import java .lang .reflect .Method ;
3839import java .net .URLDecoder ;
3940import java .net .URLEncoder ;
41+ import java .nio .charset .StandardCharsets ;
4042import java .rmi .ServerException ;
4143import java .sql .PreparedStatement ;
4244import java .sql .ResultSet ;
@@ -1875,6 +1877,18 @@ else if (recordType > 0) {
18751877 CLIENT .getMessageConverters ().forEach (converter -> {
18761878 if (converter instanceof StringHttpMessageConverter ) {
18771879 ((StringHttpMessageConverter ) converter ).setWriteAcceptCharset (false );
1880+ // 设置更大的缓冲区来处理大文本
1881+ ((StringHttpMessageConverter ) converter ).setDefaultCharset (StandardCharsets .UTF_8 );
1882+ }
1883+ });
1884+
1885+ // 添加自定义的消息转换器来处理大文本
1886+ CLIENT .getMessageConverters ().add (0 , new StringHttpMessageConverter (StandardCharsets .UTF_8 ) {
1887+ @ NotNull
1888+ @ Override
1889+ protected Long getContentLength (String s , MediaType contentType ) {
1890+ // 对于大文本,返回 null 让HTTP客户端自动处理分块传输
1891+ return s .length () > 1024 * 1024 ? -1L : super .getContentLength (s , contentType );
18781892 }
18791893 });
18801894 }
@@ -1886,6 +1900,32 @@ else if (recordType > 0) {
18861900 protected String sendRequest (HttpSession session , HttpMethod method , String url , String body , HttpHeaders headers ) {
18871901 String rspBody = null ;
18881902 try {
1903+ // 为JSON请求设置默认的Content-Type
1904+ if (body != null && method != HttpMethod .GET && !headers .containsKey (HttpHeaders .CONTENT_TYPE )) {
1905+ // 尝试解析JSON来判断内容类型
1906+ try {
1907+ JSON .parse (body );
1908+ headers .setContentType (MediaType .APPLICATION_JSON );
1909+ } catch (Exception e ) {
1910+ // 如果不是JSON,设置为普通文本
1911+ headers .setContentType (MediaType .TEXT_PLAIN );
1912+ }
1913+ }
1914+
1915+ // 设置默认的Accept header
1916+ if (!headers .containsKey (HttpHeaders .ACCEPT )) {
1917+ headers .setAccept (Arrays .asList (MediaType .APPLICATION_JSON , MediaType .TEXT_PLAIN ));
1918+ }
1919+
1920+ // 为大文本body,设置适当的Content-Type和分块传输
1921+ if (body != null && body .length () > 1024 * 1024 ) { // 超过1MB
1922+ if (!headers .containsKey (HttpHeaders .CONTENT_TYPE )) {
1923+ headers .setContentType (MediaType .TEXT_PLAIN );
1924+ }
1925+ // 设置分块传输
1926+ headers .set (HttpHeaders .TRANSFER_ENCODING , "chunked" );
1927+ }
1928+
18891929 HttpEntity <String > requestEntity = new HttpEntity <>(method == HttpMethod .GET ? null : body , headers );
18901930 ResponseEntity <String > entity = CLIENT .exchange (url , method , requestEntity , String .class );
18911931
0 commit comments