使用AsyncHttpClient从一个网站获取认证,下面是我的实现代码:
public class LoginActivity extends Activity {
String tag = "LoginActivity";
Button requestBtn;
AsyncHttpClient httpClient = new AsyncHttpClient();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
requestBtn = (Button) findViewById(R.id.upload_file);
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
httpClient.setCookieStore(myCookieStore);
httpClient.setBasicAuth(ApplicationConstants.userName,
ApplicationConstants.password, new AuthScope(
"http://*.*.*.*:8080/someUrl", 8080,
AuthScope.ANY_REALM));
requestBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
httpClient.get("http://*.*.*.*:8080/someurl",new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
Log.d("Sucessful upload","Onsucess" + response);
}
@Override
public void onFailure(Throwable arg0,String arg1) {
Log.d("LoginActivity",arg0.toString());
arg0.printStackTrace();
super.onFailure(arg0, arg1);
}
});
}
}
});
}
}
结果报出异常:
02-27 16:02:42.930: D/LoginActivity(8869): org.apache.http.client.HttpResponseException: Unauthorized
02-27 16:02:42.930: W/System.err(8869): org.apache.http.client.HttpResponseException: Unauthorized
02-27 16:02:42.930: W/System.err(8869): at com.loopj.android.http.AsyncHttpResponseHandler.sendResponseMessage(AsyncHttpResponseHandler.java:235)
02-27 16:02:42.930: W/System.err(8869): at com.loopj.android.http.AsyncHttpRequest.makeRequest(AsyncHttpRequest.java:79)
02-27 16:02:42.930: W/System.err(8869): at com.loopj.android.http.AsyncHttpRequest.makeRequestWithRetries(AsyncHttpRequest.java:95)
02-27 16:02:42.930: W/System.err(8869): at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:57)
02-27 16:02:42.930: W/System.err(8869): at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
02-27 16:02:42.930: W/System.err(8869): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-27 16:02:42.930: W/System.err(8869): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
02-27 16:02:42.940: W/System.err(8869): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
02-27 16:02:42.940: W/System.err(8869): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
02-27 16:02:42.940: W/System.err(8869): at java.lang.Thread.run(Thread.java:856)
看起来您在尝试使用AsyncHttpClient向某个URL发送HTTP GET请求,但是服务器返回了一个"Unauthorized"(未经授权)的错误。这意味着服务器需要您提供某些凭据才能访问这个URL。
您可以在AsyncHttpClient中设置基本身份验证信息,如您在代码中所示,但是这可能并不是所有服务器所需的凭据。例如,服务器可能需要您使用OAuth令牌进行身份验证,或者服务器可能需要您在请求的HTTP标头中包含一些特定的信息。
如果您确实正在使用基本身份验证,请确保您的用户名和密码是正确的,并且服务器正在使用基本身份验证。
如果您正在使用其他类型的身份验证,请确保您在AsyncHttpClient中正确设置了所需的凭据,并且在请求的HTTP标头中包含了所有必需的信息。
另外,您也可以尝试使用Fiddler或者类似的工具来捕获和分析网络请求/响应,以便了解服务器正在期望什么样的凭据。