当Java出现401未经授权的错误时,如何捕获POST请求的json响应?
我有以下API: 它用于执行身份验证,将用户名和密码作为请求正文中的参数传递,我需要获取当通知用户不正确或通知密码不正确时返回的json 在本例中,通过键入不正确的用户,我返回json:当Java出现401未经授权的错误时,如何捕获POST请求的json响应?,java,json,api,post,request,Java,Json,Api,Post,Request,我有以下API: 它用于执行身份验证,将用户名和密码作为请求正文中的参数传递,我需要获取当通知用户不正确或通知密码不正确时返回的json 在本例中,通过键入不正确的用户,我返回json: “错误”:“Usuario não registrado” 通过输入错误的密码,我得到了json返回: “错误”:“Senha inválida” 我的请求如下所示: try { String linkApi = getLinkApi().getProperty("linkApi")
“错误”:“Usuario não registrado”
通过输入错误的密码,我得到了json返回:
“错误”:“Senha inválida”
我的请求如下所示:
try {
String linkApi = getLinkApi().getProperty("linkApi");
URL url = new URL(linkApi.concat("/api/usuarios/login"));
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "application/json");
con.setRequestMethod("POST");
con.setDoOutput(true);
login = new Login();
gson = new Gson();
login.setEmail("email@email.com");
login.setPassword("senha123");
String input = gson.toJson(login);
System.out.println(input);
System.out.println("");
OutputStream os = con.getOutputStream();
os.write(input.getBytes());
os.flush();
int responseCode = con.getResponseCode();
System.out.println("Código: " + responseCode);
System.out.println("");
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
String output;
StringBuffer response = new StringBuffer();
while ((output = br.readLine()) != null) {
response.append(output);
}
br.close();
System.out.println(response.toString());
System.out.println("");
} catch(MalformedURLException e) {
System.out.println("Houve um erro. Exception: " + e.getMessage());
return false;
} catch (IOException e) {
System.out.println("Houve um erro. Exception: " + e.getMessage());
return false;
} finally {
con.disconnect();
}
在达到代码的这一部分之前,一切都进展顺利:
BufferedReader br=new BufferedReader(new InputStreamReader((con.getInputStream()))代码>
因为到达这一行时,如果错误是401,它将落入catch中,并返回我它只给出了错误401。。如何获取json?如果响应代码小于400,则可以使用getInputStream(),否则可以使用getErrorStream()而不是getInputStream()
BufferedReader br=null;
if(100)不应该假设没有json响应,因为您得到了401错误状态..未工作!通知空指针!:(如果连接未连接,或者服务器在连接时没有错误,或者服务器有错误但未发送错误数据,则getErrorStream方法将返回null.Perfect。回答正确!问题已解决,非常感谢!:D
BufferedReader br = null;
if (100 <= con.getResponseCode() && con.getResponseCode() < 400) {
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}