Sud*_*han 4 android json okhttp
我试图用OkHttp获取Web服务器响应.我现在的 minSdkVersion 15.
我的代码是
@Override
protected String doInBackground(String... strings) {
GetDataFromUrl getData = new GetDataFromUrl();
String response = null;
try {
response = getData.run(URL);
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
Run Code Online (Sandbox Code Playgroud)
和
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
Run Code Online (Sandbox Code Playgroud)
我在线上发出警告try (Response response = client.newCall(request).execute()).
它在说" Try-with-resources requires API level 19 (current min is 15).
我知道如果我将最低API级别更改为19,它将正常工作.但我必须支持min 15 API级别.
有什么解决方案吗?
小智 10
对于未来的读者.
现在,有Java 8.您只需指定使用Java 8在gradle中进行编译
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Run Code Online (Sandbox Code Playgroud)
警告将消失.编译器会将代码转换为答案中的Ted Hopp.
解决方案是不使用try-with-resources,除非您可以将min API级别设置为19.所以不要这样:
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
Run Code Online (Sandbox Code Playgroud)
你应该这样:
Response response = null;
try {
response = client.newCall(request).execute();
return response.body().string();
} finally {
if (response != null) {
response.close();
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:Java语言规范,第14.20.3.1节提供了一个略微不同(但在这种情况下,在功能上相同)等同于基本的try-with-resources语句(一个没有任何catch或finally块),就像你有:
{
final Response response = client.newCall(request).execute();
Throwable primaryExc = null;
try {
return response.body().string();
} catch (Throwable t) {
primaryExc = t;
throw t;
} finally {
if (response != null) {
if (primaryExc != null) {
try {
response.close();
} catch (Throwable suppressed) {
primaryExc.addSuppressed(suppressed);
}
} else {
response.close();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这有两个影响.首先,它使response变量本地化为等效块.(我的建议在try语句完成后使其可见,这可能是不合需要的.)更重要的是,它具有抑制关闭资源时抛出的任何异常的效果.也就是说,如果原始try块的主体抛出异常,则调用代码将看到而不是由异常抛出的异常close().(close()仍然可以通过getSuppressed()实际抛出的异常方法获得异常.)您不需要这个更复杂的版本,因为(据我从API文档中可以看出)Response.close()不会抛出异常.