Java HTTP错误代码,导致IOException-如何访问响应?
我有一个客户提出的POST请求-它可能看起来像这样:Java HTTP错误代码,导致IOException-如何访问响应?,java,http,Java,Http,我有一个客户提出的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&c
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()
if(connection.getResponseCode()>=200&&connection.getResponseCode()<400)
//然后读取connection.getInputStream()
其他的
//然后读取connection.getErrorStream()
在读取响应之前,只需检查请求是否成功,逻辑如下:
if (connection.getResponseCode() >= 200 && connection.getResponseCode() < 400)
// then read connection.getInputStream()
else
// then read connection.getErrorStream()
if(connection.getResponseCode()>=200&&connection.getResponseCode()<400)
//然后读取connection.getInputStream()
其他的
//然后读取connection.getErrorStream()
谢谢!我尝试了各种各样的方法,但你的方法立刻奏效了;)爱你(不是同性恋)谢谢!我尝试了各种各样的方法,但你的方法立刻奏效了;)爱你(不是同性恋)从找出哪条线导致问题开始从找出哪条线导致问题开始