gpt4 book ai didi

Java Post 连接使用 Try 和资源

转载 作者:行者123 更新时间:2023-12-01 06:37:45 25 4
gpt4 key购买 nike

我想使用 try 和资源来实现处理 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();
}

我对代码有以下担忧:

  1. 针对上述场景,如何在 try 和 resources 中引入条件语句?
  2. 有没有办法在尝试资源时传递连接? (可以使用嵌套的 try-catch block 来完成,因为 URL 和 HTTPConnection 不是 AutoCloseable,这本身不是一个合规的解决方案)
  3. 使用 try 和资源来解决上述问题是否是更好的方法?

最佳答案

试试这个。

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() 是一个 lambda 表达式,它在 try 语句的最后阶段执行 con.disconnect()

关于Java Post 连接使用 Try 和资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40123124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com