The HTTP header line [Content-Type: application/json: charset=utf-8] does not conform to RFC 7230 an

最近项目中遇到一件怪事,在POST请求中发现没有数据,在debug时候发现居然爆了一个retrofit2.adapter.rxjava.HttpException: HTTP 400错误。经过查阅资料发现400 请求出错
  由于语法格式有误,服务器无法理解此请求。这个错误很奇葩。把请求的完整参数发到postman中请求发现没有问题。包括使用原生的Http 写都没有问题,正在觉得怪异的时候,请求参数中|这个特殊字符串引起了我的注意。
通过在OKhttp 拦截器中打印出本次请求路径发现,所有的参数都是被编码了,但是|这个特殊字符却没有编码。

<!doctype html><html lang="en"><head><title>HTTP Status 400 – Bad Request</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 400 – Bad Request</h1><hr class="line" /><p><b>Type</b> Exception Report</p><p><b>Message</b> The HTTP header line [application&#47;json: charset=utf-8] does not conform to RFC 7230 and has been ignored.</p><p><b>Description</b> The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).</p><p><b>Exception</b></p><pre>java.lang.IllegalArgumentException: The HTTP header line [Content-Type: application&json: charset=utf-8] does not conform to RFC 7230 and has been ignored.

以下是示例修改代码
/**
 * Created by J.query on 2017/6/27.
 * email [email protected]
 */

public class HeaderInterceptor implements Interceptor {

    private Context context;

    public HeaderInterceptor(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        String name = "application/json";
        try {
            name = URLEncoder.encode(name, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Request request = original.newBuilder()
                .header(name, "charset=utf-8")
                .method(original.method(), original.body())
                .build();
        return chain.proceed(request);
    }
}

这里说一下由于Toamcat 9.0对字符做了校验,导致 "application/json" 中的“/”校验不过,所以呢

给字符处理一下就OK了。

发布了18 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/github_36787585/article/details/99452409
今日推荐