[英]Android HttpURLConnection always unauthorized 401 response (Spring Boot REST API)
我正在嘗試使用我在Android Studio中開發的Android應用程序使用REST API。 我已經使用Spring Boot開發了API。
問題:
每當我調用我的API時,我總是返回401未經授權的響應。 “調用了預先認證的入口點。拒絕訪問。”
我已將我的CORS配置如下:
cors: allowed-origins: "*" allowed-methods: GET, PUT, POST, DELETE, OPTIONS allowed-headers: "*" exposed-headers: allow-credentials: true max-age: 1800
我的api在localhost:8080上運行,並且正在使用WLAN IPv4地址從設備發出請求。
如:curl -v -X GET http://192.168.1.xx:8080 / api / users
這將返回200 OK響應。
我也可以在郵遞員/ DHC等中致電此郵件,並收到200 OK答復。
但是,當我通過android設備使用HttpURLConnection調用相同的地址時,我收到401響應。
Noob開發者在這里-關於可能導致這種情況的任何想法,將不勝感激!
編輯以包括我的GET請求:
@Override
protected String doInBackground(String... params){
String stringUrl = params[0];
String result;
String inputLine;
try {
//Create a URL object holding our url
URL myUrl = new URL(stringUrl);
//Create a connection
HttpURLConnection connect =(HttpURLConnection)
myUrl.openConnection();
connect.setRequestMethod(REQUEST_METHOD); // GET
connect.setRequestProperty("Host", HOST);
connect.setRequestProperty("Connection", "keep-alive");
connect.setRequestProperty("Origin", ORIGIN);
connect.setRequestProperty("User-Agent", System.getProperty("http.agent"));
connect.setRequestProperty("Content-Type", CONTENT_TYPE);
connect.setRequestProperty("Accept", "*/*");
connect.setRequestProperty("Accept-Encoding", ACCEPT_ENCODING);
connect.setRequestProperty("Accept-Language", ACCEPT_LANGUAGE);
connect.setDoOutput(true);
connect.setDoInput(true);
//Connect to our url
connect.connect();
String responseMessage = connect.getResponseMessage(); // Unathorized
int responseCode = connect.getResponseCode(); //401
//Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(connect.getInputStream());
//Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
//Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
//Set our result equal to our stringBuilder
result = stringBuilder.toString();
}
catch(IOException e){
e.printStackTrace();
result = null;
}
return result;
}
更換:-
InputStreamReader streamReader =新的InputStreamReader(connect.getInputStream());
帶有:-
InputStreamReader streamReader =新的InputStreamReader(connect.getErrorStram());
這將幫助您跟蹤為什么會出現401,然后才能繼續解決該問題。
401--服務器端問題,服務器無法處理您的請求,請檢查是否在使用get請求時必須在標頭或url中傳遞數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.