gpt4 book ai didi

java - Android 手机上到 Rails 服务器的基本 HTTP 身份验证

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:18:45 31 4
gpt4 key购买 nike

我正在尝试连接到需要身份验证的 Rails 应用程序服务器。我在桌面应用程序上使用 Jakarta HTTP Client for Java,它可以 100% 运行。但是当在 Android Emulator 上执行完全相同的代码时,我得到一个 IOException。

这是代码,如果有人能帮我弄清楚它抛出 IOException 的原因,我将不胜感激!

private boolean login()
{
String username, password;

DefaultHttpClient client;
AuthScope scope;
Credentials myCredentials;
CredentialsProvider provider;
HttpEntity entity;
String line;
BufferedReader reader;
InputStream instream;

//Declare & Create the HTTP Client
client = new DefaultHttpClient();

//Create our AuthScope
scope = new AuthScope("10.19.9.33", 3000);

username = "admin"
password = "pass"


//Set Credentials
myCredentials = new UsernamePasswordCredentials( username, password );

//Set Provider
provider = new BasicCredentialsProvider();
provider.setCredentials(scope, myCredentials);

//Set Credentials
client.setCredentialsProvider( provider );

String url = "http://10.19.9.33:3000/users/show/2";

HttpGet get;

//Tell where to get
get = new HttpGet( url );

HttpResponse response;

try
{
response = client.execute( get );

entity = response.getEntity();

/* Check to see if it exists */
if( entity != null )
{
instream = entity.getContent();

try {

reader = new BufferedReader(new InputStreamReader(instream));

line = reader.readLine();

if( line.equals( "HTTP Basic: Access denied.") )
return false;

while ( line != null )
{
// do something useful with the response
System.out.println(line);

line = reader.readLine();
}

return true;

}
catch (IOException ex)
{

// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;

}
catch (RuntimeException ex)
{
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection and release it back to the connection manager.
get.abort();
throw ex;
}
finally
{
// Closing the input stream will trigger connection release
instream.close();
}
}
}
catch( ClientProtocolException cp_ex )
{

}
catch( IOException io_ex )
{

}

return false;
}

最佳答案

它一直触发 IOException 的原因是因为 Manifest 文件没有给应用程序访问互联网的权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

关于java - Android 手机上到 Rails 服务器的基本 HTTP 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4269854/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com