我是这个网站的新手,所以如果我做错了,请告诉我。
我正在尝试在我的node.js服务器和我的Android应用程序之间建立连接。例如,我正在尝试连接一个名为showWithAuth的页面,我需要使用摘要策略进行身份验证。
为此我使用Authenticator:
Authenticator.setDefault(new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication (username, password.toCharArray());
// System.out.println(pa.getUserName() + ":" + new String(pa.getPassword()));
}
});
我真正的问题是当我尝试建立连接时:
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(connection
.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
/*connection.setInstanceFollowRedirects(false);
int status = connection.getResponseCode();
InputStream is;
if (status >= 400 && status <= 499) {
throw new Exception("Bad authentication status: " + status); //provide a more meaningful exception message
}
else
{*/
//connection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
//connection.setRequestProperty("Accept", "*/*");
/*is = connection.getInputStream();
}
byte[] buffer = new byte[8196];
int readCount;
final StringBuilder builder = new StringBuilder();
while ((readCount = is.read(buffer)) > -1) {
builder.append(new String(buffer, 0, readCount));
}
String response = builder.toString();
System.out.println(response);*/
} catch (java.net.ProtocolException e) {
sb.append("User Or Password is wrong!");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
我遇到的问题是filenotfoundexception,在这一行:.getInputStream()));
服务器的响应是401:身份验证状态错误
我看到有些人遇到了同样的问题,但我尝试了所有解决方案而没有得到更好的解决方案。
如果你能帮助我弄错我做错的事!谢谢!
PS:还尝试了评论代码。
PS2:很抱歉这么久。编辑:只是说这段代码只适用于带有Java的Netbeans,但不适用于Android Studio
答案 0 :(得分:0)
请尝试添加
<uses-permission android:name="android.permission.INTERNET" />
对于AndroidManifest.xml文件,这可以解决您的问题。