Okhttp3作为一个Android开源网络框架,已经被广泛应用了,版本也是常有更新,比如说从3.13.0之后不再支持android5.0以下的系统。
能够广泛使用,充分说明了它的实用性,但正是它的广泛使用,我遇到了一些兼容性问题。项目使用的不同包,他们使用的Okhttp3版本差异使得无法兼容。一般遇到这样的问题,容易让人爆粗口,还好我比较淡定。
举两个碰到的例子,版本3.8.1 RealResponseBody的构造方法时这样的
public RealResponseBody(Headers headers, BufferedSource source)
版本3.9.1 RealResponseBody的构造方法变成了这样
public RealResponseBody(
@Nullable String contentTypeString, long contentLength, BufferedSource source)
版本3.11.0
okhttp3.MediaType 新增了一个get(String string)方法,我碰到过第三方包使用get导致不兼容的问题
/**
* Returns a media type for {@code string}.
*
* @throws IllegalArgumentException if {@code string} is not a well-formed media type.
*/
public static MediaType get(String string) {
Matcher typeSubtype = TYPE_SUBTYPE.matcher(string);
if (!typeSubtype.lookingAt()) {
throw new IllegalArgumentException("No subtype found for: \"" + string + '"');
}
String type = typeSubtype.group(1).toLowerCase(Locale.US);
String subtype = typeSubtype.group(2).toLowerCase(Locale.US);
String charset = null;
Matcher parameter = PARAMETER.matcher(string);
for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) {
parameter.region(s, string.length());
if (!parameter.lookingAt()) {
throw new IllegalArgumentException("Parameter is not formatted correctly: \""
+ string.substring(s)
+ "\" for: \""
+ string
+ '"');
}
String name = parameter.group(1);
if (name == null || !name.equalsIgnoreCase("charset")) continue;
String charsetParameter;
String token = parameter.group(2);
if (token != null) {
// If the token is 'single-quoted' it's invalid! But we're lenient and strip the quotes.
charsetParameter = (token.startsWith("'") && token.endsWith("'") && token.length() > 2)
? token.substring(1, token.length() - 1)
: token;
} else {
// Value is "double-quoted". That's valid and our regex group already strips the quotes.
charsetParameter = parameter.group(3);
}
if (charset != null && !charsetParameter.equalsIgnoreCase(charset)) {
throw new IllegalArgumentException("Multiple charsets defined: \""
+ charset
+ "\" and: \""
+ charsetParameter
+ "\" for: \""
+ string
+ '"');
}
charset = charsetParameter;
}
return new MediaType(string, type, subtype, charset);
}
/**
* Returns a media type for {@code string}, or null if {@code string} is not a well-formed media
* type.
*/
public static @Nullable MediaType parse(String string) {
try {
return get(string);
} catch (IllegalArgumentException ignored) {
return null;
}
}