20170906工作日记--volley源码的相关方法细节学习

时间:2021-12-15 07:02:29

1. 在StringRequest类中的75行--new String();使用方法

  /**
* 工作线程将会调用这个方法
* @param response Response from the network
* @return
*/
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {//如果指定字符集不受支持
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}

关于HttpHeaderParser.parseCharaset()方法:

     /**
* Retrieve a charset from headers
*
* @param headers An {@link java.util.Map} of headers
* @param defaultCharset Charset to return if none can be found
* @return Returns the charset specified in the Content-Type of this header,
* or the defaultCharset if none can be found.
*/
public static String parseCharset(Map<String, String> headers, String defaultCharset) {
String contentType = headers.get(HTTP.CONTENT_TYPE);
if (contentType != null) {
String[] params = contentType.split(";");
for (int i = 1; i < params.length; i++) {
String[] pair = params[i].trim().split("=");
if (pair.length == 2) {
if (pair[0].equals("charset")) {
return pair[1];
}
}
}
} return defaultCharset;
} /**从请求消息头中获取编码字符集,并且返回
* Returns the charset specified in the Content-Type of this header,
* or the HTTP default (ISO-8859-1) if none can be found.
*/
public static String parseCharset(Map<String, String> headers) {
return parseCharset(headers, HTTP.DEFAULT_CONTENT_CHARSET);
}

(1)需要了解到HTTP协议中HTTP.CONTENT_TYPE参数以及HTTP协议的消息头信息:

20170906工作日记--volley源码的相关方法细节学习

20170906工作日记--volley源码的相关方法细节学习

可以看到Content-type的消息格式为application/json;chaset=UTF-8 的格式

(2)new String(byte[],"UTF-8")是新建了一个UTF-8编码的字符串

字符串内容不变,只是依照后面的字符集创建新的字符串,其中解决中文乱码问题可以使用GBK字符编码。

同时它将抛出:UnsupportedEncodingException - 如果指定字符集不受支持