java HTTP错误代码,导致IOException如何访问响应?
我有一个由客户提出的发帖请求——它可能看起来像这样:
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();
}
# 1 楼答案
在读取响应之前,只需检查请求是否成功,逻辑如下: