我有一个 POST 请求,由客户端发出 - 它可能看起来像这样:
https://www.pollmc.com/api/v1/poll.php
PARAMS
question = Question
answers = ["Yes","No"]
oip = true
secret = false
displayname = Chris
而且我正在做测试,我已经禁止了自己(返回 403 错误)。但是,当它确实返回错误时,java 会导致 IOException 错误(在我的 try & catch 中)。我怎样才能阻止它导致错误,或者如何获得响应,以便我可以将它发送给客户,告诉他们他们做错了什么。
这是我的代码
try {
urlParams = URLEncoder.encode(urlParams, "UTF-8");
URL urlObject = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(urlParams.length()));
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
OutputStream os = connection.getOutputStream();
os.write(urlParams.getBytes());
StringBuilder responseSB = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ( (line = br.readLine()) != null)
responseSB.append(line);
br.close();
os.close();
this.response = responseSB.toString();
this.responseCode = connection.getResponseCode();
} catch(IOException e) {
e.printStackTrace();
}
最佳答案
在读取响应之前简单的检查请求是否成功,逻辑如下:
if (connection.getResponseCode() >= 200 && connection.getResponseCode() < 400)
// then read connection.getInputStream()
else
// then read connection.getErrorStream()
关于java - HTTP 错误代码,导致 IOException - 如何访问响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37397578/