【OkHttpClient Content-Type addNetworkInterceptor addInterceptor consumes】

consumes

这里的是后续补充的
突然发现,可以直接用consumes 就能改请求头……用啥拦截器,太傻逼,直接consumes 然后每个请求就可以用不同的Content-Type类型(注意需要把拦截器中的修改Content-Type去掉,要不应该会覆盖),不过下面的这个可以当个输出请求的curl

@PostMapping(value = "/v1/aa", consumes = MediaType.APPLICATION_JSON_VALUE)

OkHttpClient 请求头

OkHttpClient请求头默认是text/plain;charset=utf-8……吐了,正常需求的是application/json

应用拦截器(addInterceptor)
主要用于查看请求信息及返回信息,如链接地址、头信息、参数信息等
网络拦截器(addNetworkInterceptor)
可以添加、删除或替换请求头信息,还可以改变的请求携带的实体

所以,最好还是用addNetworkInterceptor,可以修改请求头,同样也能输出日志,用addInterceptor(好像就是修改的缓存)修改header头后,你会发现最终请求还是text/plain;charset=utf-8,没毛线用,而且输出的curl信息好像也是缓存的请求信息,根本不是真是的请求信息

注意:addNetworkInterceptor(好像是直接在网络发送请求前)最好是可以连接到请求,因为好像连接不到,不会输出信息,而addInterceptor……连接失败也会输出信息的,就是不太准确,毕竟好像是类似缓存的请求信息

最重要的一点,chagpt……特喵有时候给不准确的答案,他竟然不知道addInterceptor基本是用来做查看的,坑死我了

package com.ctct.scan.wingshield.biz.dependence.config;


import okhttp3.*;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Feign配置,OkHttpClient
 */
@Configuration
public class FeignOkConfig {

    private static final Logger logger = LoggerFactory.getLogger(FeignOkConfig.class);
    @Bean
    public OkHttpClient okHttpClient() {
        // 创建 OkHttpClient 实例,并配置默认请求头
        return new OkHttpClient.Builder()
                .addNetworkInterceptor(chain -> {
                    Request originalRequest = chain.request();
                    Request modifiedRequest = originalRequest.newBuilder()
                            .header("Content-Type", "application/json")
                            .build();

                    return chain.proceed(modifiedRequest);
                })
                .addNetworkInterceptor(new CurlLoggingInterceptor())
                .build();
    }

    private static class CurlLoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            // 构建 curl 参数
            StringBuilder curlCommand = new StringBuilder("curl ");
            curlCommand.append("-X ").append(request.method()).append(" ");

            // 添加请求头
            for (String name : request.headers().names()) {
                String value = request.headers().get(name);
                curlCommand.append("-H '").append(name).append(": ").append(value).append("' ");
            }

            // 添加请求体
            RequestBody requestBody = request.body();
            if (requestBody != null) {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);
                Charset charset = Charset.forName("UTF-8");
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(charset);
                }
                curlCommand.append("-d '").append(buffer.readString(charset)).append("' ");
            }

            // 添加请求 URL
            curlCommand.append("'").append(request.url()).append("'");

            // 打印 curl 命令
//            System.out.println("curl command: " + curlCommand.toString());
            logger.info("curl command: " + curlCommand.toString());

            Response response = chain.proceed(request);

            return response;
        }
    }

}

最终请求效果图

curl -X GET -H "Content-Type: application/json" -H "Authorization: Bearer <token>" "https://api.example.com/endpoint"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值