【发布时间】:2016-12-18 07:18:48
【问题描述】:
我正在尝试将 REST API 与我在 Android Studio 中开发的 Android 应用程序一起使用。我已经使用 Spring Boot 开发了 API。
问题:
每当我调用我的 API 时,总是会返回 401 Unauthorized 响应。 “调用了预先验证的入口点。拒绝访问。”
我的 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 响应。
这里是新手开发人员 - 任何关于可能导致此问题的想法都将不胜感激!
编辑以包含我的 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;
}
【问题讨论】:
-
这可能对你有帮助 - stackoverflow.com/questions/6176609/…
-
替换:- InputStreamReader streamReader = new InputStreamReader(connect.getInputStream());使用:- InputStreamReader streamReader = new InputStreamReader(connect.getErrorSram());这将帮助您跟踪 401 的原因,然后您可以继续解决该问题。 401--是服务器端问题,服务器无法处理你的请求,检查你在使用get请求时是否必须在header或url中传递数据
标签: java android spring rest api