2016-10-19 3 views
0

リソースを使ってtryを使ってPOSTリクエストを処理するコードを実装したいと思います。続きJavaポスト接続リソースを使って試してみよう

は私のコードです:

public static String sendPostRequestDummy(String url, String queryString) { 
    log.info("Sending 'POST' request to URL : " + url); 
    log.info("Data : " + queryString); 
    BufferedReader in = null; 
    HttpURLConnection con = null; 
    StringBuilder response = new StringBuilder(); 
    try{ 
     URL obj = new URL(url); 
     con = (HttpURLConnection) obj.openConnection(); 
     // add request header 
     con.setRequestMethod("POST"); 
     con.setRequestProperty("User-Agent", "Mozilla/5.0"); 
     con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); 
     con.setRequestProperty("Content-Type", "application/json"); 
     // Send post request 
     con.setDoOutput(true); 
     DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
     wr.writeBytes(queryString); 
     wr.flush(); 
     wr.close(); 
     int responseCode = con.getResponseCode(); 
     log.info("Response Code : " + responseCode); 
     if (responseCode >= 400) 
      in = new BufferedReader(new InputStreamReader(con.getErrorStream())); 
     else 
      in = new BufferedReader(new InputStreamReader(con.getInputStream())); 

     String inputLine; 

     while ((inputLine = in.readLine()) != null) { 
      response.append(inputLine); 
     } 
    }catch(Exception e){ 
     log.error(e.getMessage(), e); 
     log.error("Error during posting request"); 
    } 
    finally{ 
     closeConnectionNoException(in,con); 
    } 
    return response.toString(); 
} 

私はコードの次の問題があります。上記のシナリオのためのリソースを試しに条件文を導入する方法

  1. を?
  2. リソースを試して接続を渡す方法はありますか? (URLとHTTPConnectionはAutoCloseableではないため、ネストされたtry-catchブロックを使用して行うことができます)。
  3. 上記の問題に対するリソースを試してみるのが良い方法ですか?

答えて

0

1:try内の条件文もリソース文で使用できます。残念ながら、このブロックには新しい変数を定義する必要があり、あらかじめ定義された変数を使用することはできません。 (あなたのコード内の変数in

try (BufferedReader in = (responseCode >= 400 ? new BufferedReader(new InputStreamReader(con.getErrorStream())) : new BufferedReader(new InputStreamReader(con.getInputStream())))) { 
    // your code for getting string data 
} 

2:私は、HttpUrlConnectionAutoCloseableあるか分からない、だから、disconnect()自分を呼び出すためには良い考えかもしれません。私はこのことについて何か提案しています。

3:tryとリソースは間違いなくリソースの管理に役立ちます。しかし、使用後にリソースを適切に解放していると確信していれば、コードは正常です。

3

これを試してください。

HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
try (AutoCloseable conc =() -> con.disconnect()) { 
    // add request headers 
    try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) { 
     wr.writeBytes(queryString); 
    } 
    int responseCode = con.getResponseCode(); 
    try (InputStream ins = responseCode >= 400 ? con.getErrorStream() : con.getInputStream(); 
     BufferedReader in = new BufferedReader(new InputStreamReader(ins))) { 
     // receive response 
    } 
} 

() -> con.disconnect() try文の最後に、ステージでcon.disconnect()を実行ラムダ式です。

+0

ほとんどのクエリで問題ありません。しかし、ネストされたメソッドを使用して良いアプローチを試していますか?私のコードはtry-catch-finallyでうまくいきます。このアプローチの利点は何ですか? –

+0

@Chinmayjainあなた/他の人がコードをコピーペーストすると、1つのモノリシックブロックとして表示されます。 – Koshinae

関連する問題