当 Java 出现 401 Unauthorized 错误时,如何捕获 POST 请求的 json 响应?

How do I capture the json response of a POST request when the 401 Unauthorized error occurs with Java?

我有以下 API:

https://mrcheff.herokuapp.com/v1/api/usuarios/login

用于在请求正文中将用户名和密码作为参数进行身份验证,当通知用户不正确或通知密码为return时,我需要获取json不正确!

在这种情况下,通过输入错误的用户,我 return json:

"errors": "Usuario não registrado"

通过输入错误的密码,我得到 json return:

"errors": "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,它就会落入陷阱并且 return 告诉我它给出了错误 401 .. 我如何得到 json'小号?

如果响应代码小于 400,您可以使用 getInputStream(),否则您可以使用 getErrorStream() 而不是 getInputStream()。

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()));
}

如果连接未连接,或者连接时服务器没有错误,或者服务器有错误但没有发送错误数据,getErrorStream 方法将return null。