最近項目中遇到一件怪事,在POST請求中發現沒有資料,在debug時候發現居然爆了一個retrofit2.adapter.rxjava.HttpException: HTTP 400錯誤。經過查閱資料發現400 請求出錯
由于文法格式有誤,伺服器無法了解此請求。這個錯誤很奇葩。把請求的完整參數發到postman中請求發現沒有問題。包括使用原生的Http 寫都沒有問題,正在覺得怪異的時候,請求參數中|這個特殊字元串引起了我的注意。
通過在OKhttp 攔截器中列印出本次請求路徑發現,所有的參數都是被編碼了,但是|這個特殊字元卻沒有編碼。
<!doctype html><html ><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/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了。