简体   繁体   English

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

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

I have the following API:我有以下 API:

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

It is used to perform authentication passing username and password as parameters in the request body and I need to get the json that returns when the informed user is incorrect or the informed password is incorrect!它用于在请求正文中通过用户名和密码作为参数执行身份验证,我需要获取当通知用户错误或通知密码错误时返回的 json!

In this case, by typing the incorrect user, I return the json:在这种情况下,通过输入不正确的用户,我返回 json:

"errors": "Usuario não registrado"

And by typing the wrong password I get the json return:通过输入错误的密码,我得到 json 返回:

"errors": "Senha inválida"

My request looks like this:我的请求如下所示:

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

Everything flows well until you get to that part of the code:一切顺利,直到您到达代码的那部分:

BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));

Because arriving at this line, if the error is 401, it falls in the catch and returns me only that it gave the error 401.. how do I get the json's?因为到达这一行,如果错误是 401,它会被捕获并只返回给我它给出了错误 401 .. 我如何获得 json 的?

If the response code is less than 400 you can use getInputStream() otherwise you can use getErrorStream() instead of getInputStream().如果响应代码小于 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()));
}

If the connection was not connected, or if the server did not have an error while connecting or if the server had an error but no error data was sent, getErrorStream method will return null.如果连接没有连接,或者服务器在连接时没有错误,或者服务器有错误但没有发送错误数据,getErrorStream 方法将返回 null。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Java 中发布请求以获取 JSON 中的响应 - How to post request in java to get the response in JSON 尝试在 springboot API 中 POST 时,如何在 401 Unauthorized 错误上记录请求的有效负载详细信息 - How to log requested payload details on 401 Unauthorized error when try to POST in springboot API 如何捕获Java中的SOAP请求和响应消息? - How can I capture SOAP request and response messages in Java? HTTP 401 在 Spring 启动测试中出现未经授权的错误 - HTTP 401 Unauthorized error occurs in Spring Boot test 云端点返回错误401未经授权的请求 - cloud endpoints return error 401 unauthorized request 面向响应代码401响应消息为移动应用程序运行负载测试时出现未经授权的错误 - Facing Response code 401 Response message Unauthorized error when running load test for mobile application 我如何修复 Spring 引导上的“错误 401 未经授权” - how can i fix “Error 401 Unauthorized” on Spring Boot 如何通过 java 代码在响应不是 200 的调用后捕获错误响应正文和错误代码? - How to capture error response body and error code in post call where the response is not 200 via java code? 通过POST访问URL时出现“传输错误:401错误:未经授权” - Getting “Transport error: 401 Error: Unauthorized” when accessing URL through POST 当 HTTP 请求返回状态为 401 时,如何在 Java 中解析响应正文 - How to parse the response body in Java, when the HTTP request has return status 401
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM