[英]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
它用於在請求正文中通過用戶名和密碼作為參數執行身份驗證,我需要獲取當通知用戶錯誤或通知密碼錯誤時返回的 json!
在這種情況下,通過輸入不正確的用戶,我返回 json:
"errors": "Usuario não registrado"
通過輸入錯誤的密碼,我得到 json 返回:
"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,它會被捕獲並只返回給我它給出了錯誤 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 方法將返回 null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.