对,我一直在努力尝试找出 android 中的基本身份验证,以便我可以从 url 中提取 json 数据。到目前为止,基本身份验证似乎给我带来了很多麻烦。最后经过三天的研究,我在网上找到了一个使用类似技术来下拉 xml 的示例。这就是我所拥有的:
String MY_APP_TAG = "basic.authentication";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String username = "username";
String host = "www.example.com";
String password = "password";
String urlBasePath = "http://www.example.com/api/core/v1/my";
String urlApiCall_FindAllRepositories = urlBasePath;
try {
HttpClient client = new DefaultHttpClient();
AuthScope as = new AuthScope(host, 80);
UsernamePasswordCredentials upc = new UsernamePasswordCredentials(
username, password);
((AbstractHttpClient) client).getCredentialsProvider()
.setCredentials(as, upc);
BasicHttpContext localContext = new BasicHttpContext();
BasicScheme basicAuth = new BasicScheme();
localContext.setAttribute("preemptive-auth", basicAuth);
HttpHost targetHost = new HttpHost(host, 80, "http");
HttpGet httpget = new HttpGet(urlApiCall_FindAllRepositories);
HttpResponse response = client.execute(targetHost, httpget,
localContext);
HttpEntity entity = response.getEntity();
Object content = EntityUtils.toString(entity);
String decoded_password = new String(Base64.decode(content.toString(), Base64.DEFAULT));
System.out.println("RESULT: " + decoded_password);
Log.d(MY_APP_TAG, content.toString());
System.out.println(content.toString().getBytes().toString());
} catch (Exception e) {
e.printStackTrace();
Log.d(MY_APP_TAG, "Error: " + e);
}
}
}
正如您从代码中看到的那样,我正在通过身份验证并尝试使用 base 64 解码结果。奇怪的是,这就是我要返回的内容:
07-04 21:55:01.726:D/gralloc_goldfish(639):没有检测到 GPU 仿真的仿真器。
07-04 21:58:19.256: I/dalvikvm(753): threadid=3: 对信号 3 做出反应
07-04 21:58:19.297: I/dalvikvm(753): 将堆栈跟踪写入“/data/anr/traces.txt”
07-04 21:58:19.656:W/DefaultRequestDirector(753):身份验证错误:无法响应任何这些质询:{}
07-04 21:58:19.676:I/System.out(753):结果:“N�7��|�22”</p>
07-04 21:58:19.676: D/basic.authentication(753): ������������1Â0��÷¼ÂÊÒ!
07-04 21:58:19.676: D/basic.authentication(753): &ÄÄʬÄ4L¶£¿²îÎÊ
07-04 21:58:19.676: D/basic.authentication(753): 2Ëzc¦ùN&]]jð@6ÚOçð ��ñIf¸PÄKì^¨yMè¡é(½{ÕjÑ< `J£/C _RÇÝöLÿããaÃ÷²� ����
07-04 21:58:19.676: I/System.out(753): [B@412d87a0
07-04 21:58:19.746: I/dalvikvm(753): threadid=3: 对信号 3 做出反应
07-04 21:58:19.756: I/dalvikvm(753): 将堆栈跟踪写入“/data/anr/traces.txt”
07-04 21:58:19.946:D/gralloc_goldfish(753):没有检测到 GPU 仿真的仿真器。
如您所见,我收到了一些奇怪的代码,但它也说明存在身份验证错误。
谁能帮我弄清楚发生了什么?