【发布时间】:2013-06-11 20:29:54
【问题描述】:
我是 android 新手,这是我在 android 上的第一个项目。我在“身份验证”问题上苦苦挣扎了一天多。我尝试了几种选择,但都没有奏效。
基本上,我想调用 REST API 并获得响应。我确信 API 没有问题,因为我在另一个 iOS 应用程序中使用了相同的 API。
我通过了授权标头,但仍然进行身份验证,未显示任何找到的消息。我在 stackoverflow 上发现了一些与此相关的问题,但其中一些不起作用,而有些对我来说没有意义。
我得到状态码401。我知道这意味着要么没有通过身份验证,要么如果通过了,那么它们是错误的。在这里,我确信我通过的是正确的。
下面是我的代码:
try {
url = new URL(baseUrl);
}
catch (MalformedURLException me) {
Log.e(TAG, "URL could not be parsed. URL : " + baseUrl + ". Line : " + getLineNumber(), me);
me.printStackTrace();
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setConnectTimeout(TIMEOUT * 1000);
urlConnection.setChunkedStreamingMode(0);
// Set HTTP headers
String authString = "username:password";
String base64Auth = Base64.encodeToString(authString.getBytes(), Base64.DEFAULT);
urlConnection.setRequestProperty("Authorization", "Basic " + base64Auth);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Content-type", "application/json");
if (method.equals("POST") || method.equals("PUT")) {
// Set to true when posting data
urlConnection.setDoOutput(true);
// Write data to post to connection output stream
OutputStream out = urlConnection.getOutputStream();
out.write(postParameters.getBytes("UTF-8"));
}
try {
// Get response
in = new BufferedInputStream(urlConnection.getInputStream());
}
catch (IOException e) {
Log.e(TAG, "Exception in getting connection input stream. in : " + in);
e.printStackTrace();
}
// Read the input stream that has response
statusCode = urlConnection.getResponseCode();
Log.d(TAG, "Status code : " + statusCode);
}
catch (ProtocolException pe) {
pe.printStackTrace();
}
catch (IllegalStateException ie) {
ie.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
看看 logcat 的截图:
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
String authString = "用户名:密码";这个“用户名:密码”应该等于他们在网站开发者模型中的意思的字符串。例如:他们可能会这样使用 Loginid:password。
-
@Akash 你找到解决方案了吗?
-
@AsafK 原因是 HttpUrlConnection 引发了状态码 400 及以上的异常。我们需要处理这个异常。就我而言,我最终使用了 HttpClient 而不是 HttpUrlConnetion,因为它可以处理所有状态代码。
-
@Akash 我得到的 401 是因为这是我在凭据错误的情况下发回的内容。我只是想知道错误消息(“未找到身份验证挑战。”),这对我来说似乎太笼统了。无论如何,根据您所说的,在我需要处理的情况下会发生 IOException 。谢谢。
-
你能解决它吗?
标签: java android authentication httpurlconnection ioexception