【发布时间】:2016-10-19 05:45:20
【问题描述】:
我想使用资源尝试实现处理 POST 请求的代码。
以下是我的代码:
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 with resources 是更好的方法吗?
【问题讨论】:
标签: java exception-handling try-catch try-with-resources