2016-11-03 13 views
1

私はOkHttpでWebサーバーの応答を取得しようとしています。 私の現在のminSdkVersion 15リソースの試用にはAPIレベル19(OkHttp)が必要です

私のコードは、私はラインtry (Response response = client.newCall(request).execute())で警告を取得しています

@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-with-resources requires API level 19 (current min is 15)を言っている。

を私は19に最小APIレベルを変更した場合、それが正常に動作しますことを知っている。しかし、私は15分のAPIレベルをサポートする必要があります。

は、任意の解決策はあります?

答えて

5

ソリューションは、あなたはので、代わりにこのの19にあなたの分のAPIレベルを設定することができない限り、トライして、リソース使用しないことです。

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

あなたがすべきこれまでに:あなたのようなJava Language Specification, Section 14.20.3.1が基本のtry-と資源文と同じわずかに異なる(しかし、この場合は、機能的に同一)を提供(任意のcatchまたはfinallyブロックなし1)している:

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

EDIT

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

これには2つの効果があります。まず、responseを等価ブロックのローカル変数にします。 (私の提案は、tryステートメントが終了した後に表示され、望ましくない可能性があります)。さらに重要なことは、リソースを閉じるときにスローされた例外をすべて抑制することです。つまり、元のtryブロックの本体が例外をスローした場合、コードを呼び出すと、close()によってスローされた例外の代わりにそのコードが表示されます。 (close()によってスローされた例外は、実際にスローされた例外のgetSuppressed()メソッドを介して依然として利用可能です。)この複雑なバージョンは必要ありません。(私がAPIドキュメントから知る限り)Response.close()は例外をスローしません。 。

+0

ありがとうございます。 :) – Sudarshan

関連する問題