Android这边使用的是OKHTTP3作为网络框架的,我查了一下发现它的默认编码就是UTF-8,请求时使用了一个工具类来提交POST请求,代码如下:
public static Object[] postHttp(Context context, String url, HashMap<String, String> params, String cachetype, int cacheseconds) {
try {
// 缓存文件夹
File cacheFile = new File(context.getExternalCacheDir().toString(), "cache");
// 缓存大小为50M
int cacheSize = 50 * 1024 * 1024;
// 创建缓存对象
final Cache cache = new Cache(cacheFile, cacheSize);
OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.cache(cache)
.build();
FormBody.Builder formBodyBuilder = new FormBody.Builder();
for (Map.Entry<String, String> entry : params.entrySet())
formBodyBuilder.add(entry.getKey(), entry.getValue());
RequestBody formBody = formBodyBuilder.build();
CacheControl cacheControl = null;
if (cachetype.equals(TYPE_CACHE_CONTROL)) {
cacheControl = new CacheControl.Builder()
.maxAge(cacheseconds, TimeUnit.SECONDS).build();
}
if (cachetype.equals(TYPE_FORCE_CACHE)) {
cacheControl = FORCE_CACHE;
}
if (cachetype.equals(TYPE_FORCE_NETWORK)) {
cacheControl = FORCE_NETWORK;
}
Request request = new Request.Builder()
.cacheControl(cacheControl)
.url(url)
.post(formBody)
.build();
Response response = mOkHttpClient.newCall(request).execute();
String result = response.body().string();
// ...
} catch (Exception e) {
// ...
}
}
JAVA后台已经设置了编码:
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
TOMCAT中的server.xml中也进行了设置:
<Connector port="8080" protocol="HTTP/1.1"
useBodyEncodingForURI="true"
URIEncoding="utf-8"
connectionTimeout="20000"
redirectPort="8443" />
Android上传中文的时候,服务器接收到的是%E5%95%A6%E5%95%A6%E5%95%A6这样的编码。
这个问题困扰了我很久,请问有大神知道解决方案吗?