2016-11-03 44 views
1

我試圖使用OkHttp獲得Web服務器響應。 我的當前minSdkVersion 15試用資源需要API級別19(OkHttp)

我的代碼是

@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; 
    } 

而且

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(); 
     } 
    } 

我在該行try (Response response = client.newCall(request).execute())得到一個警告。

它說:「Try-with-resources requires API level 19 (current min is 15)

我知道,如果我改變最小API等級19,它會很好地工作,但我要支持分15 API級別。

有沒有什麼解決方案?

回答

5

的解決方案是不使用try-與資源,除非你可以設置你分鐘API級到19所以不是這樣的:

try (Response response = client.newCall(request).execute()) { 
    return response.body().string(); 
} 

你應該這樣:

Response response = null; 
try { 
    response = client.newCall(request).execute(); 
    return response.body().string(); 
} finally { 
    if (response != null) { 
     response.close(); 
    } 
} 

編輯:Java Language Specification, Section 14.20.3.1提供了一個稍微不同的(但是,在這種情況下,功能相同),相當於一個基本的嘗試,與資源的語句(一個沒有任何catchfinally塊),如您有:

{ 
    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(); 
      } 
     } 
    } 
} 

這有兩個效果。首先,它使response局部變量爲等效塊。 (我的建議在try語句結束後可見,這可能是不可取的。)更重要的是,它具有抑制關閉資源時引發的任何異常的效果。也就是說,如果原始try塊的主體引發異常,調用代碼將會看到,而不是close()拋出的異常。 (close()引發的異常仍然可以通過實際拋出的異常的getSuppressed()方法得到。)您不需要這個更復雜的版本,因爲(據我所知,API文檔)Response.close()不會拋出異常。

+0

謝謝,它的工作。 :) – Sudarshan

相關問題