[英]Android http basic authentication
I have a problem with the Android http url connection. 我的Android http网址连接有问题。 I have this method:
我有这种方法:
private String getHtml(String urlString) throws Exception {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
URL url = new URL(urlString);
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", "Basic " + password);
InputStream content = uc.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = in.readLine()) != null) {
pw.println(line);
}
return sw.toString();
}
When I use it from a normal java application it works just fine. 当我从普通的Java应用程序中使用它时,它就可以正常工作。 But when I run it from within an Android application it doesn't work.
但是,当我从Android应用程序中运行它时,它不起作用。
I have observed that the url connection is an org.apache...HttpURLConnection when run in Android. 我观察到,在Android中运行时,URL连接是org.apache ... HttpURLConnection。 And when it uses this it doesn't enter the while-loop.
而且,当使用它时,它不会进入while循环。
In the normal java application it uses a sun.net...HttpURLConnection (which works). 在普通的Java应用程序中,它使用sun.net ... HttpURLConnection(有效)。
Anyone have any suggestions to how I can get this to work on Android? 有人对我如何使它在Android上运行有任何建议吗?
You could try this solution: 您可以尝试以下解决方案:
try
{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
}
catch (Exception e)
{
// Code
}
Can't remember the correct Exception at the moment, but I think you could find it. 目前无法记住正确的Exception,但我认为您可以找到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.