我想實現用資源嘗試處理POST請求的代碼。Java Post Connection使用試用資源
以下是我的代碼:
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();
}
我的代碼如下擔憂:
- 怎樣在嘗試資源條件語句對於上述方案?
- 有沒有辦法在嘗試使用資源時傳遞連接? (可以使用嵌套的try-catch塊來完成,因爲URL和HTTPConnection不是AutoCloseable,它本身不是一個兼容的解決方案)
- 正在使用試用資源來解決上述問題是一種更好的方法嗎?
這對我的大部分查詢都很好。但是,使用嵌套嘗試一個好方法?我的意思是我的代碼在try-catch-finally中正常工作。這種方法的優點是什麼? –
@Chinmayjain如果您/某人複製代碼,它將顯示爲一個整體塊。 – Koshinae