リソースを使って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();
}
私はコードの次の問題があります。上記のシナリオのためのリソースを試しに条件文を導入する方法
- を?
- リソースを試して接続を渡す方法はありますか? (URLとHTTPConnectionはAutoCloseableではないため、ネストされたtry-catchブロックを使用して行うことができます)。
- 上記の問題に対するリソースを試してみるのが良い方法ですか?
ほとんどのクエリで問題ありません。しかし、ネストされたメソッドを使用して良いアプローチを試していますか?私のコードはtry-catch-finallyでうまくいきます。このアプローチの利点は何ですか? –
@Chinmayjainあなた/他の人がコードをコピーペーストすると、1つのモノリシックブロックとして表示されます。 – Koshinae