【问题标题】:Android http basic authenticationAndroid http基本认证
【发布时间】:2012-01-06 17:24:42
【问题描述】:

我的 Android http url 连接有问题。 我有这个方法:

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();
}

当我从普通的 java 应用程序中使用它时,它工作得很好。 但是当我在 Android 应用程序中运行它时,它就不起作用了。

我观察到,在 Android 中运行时,url 连接是 org.apache...HttpURLConnection。当它使用它时,它不会进入while循环。

在普通的 java 应用程序中,它使用 sun.net...HttpURLConnection(有效)。

有人对我如何让它在 Android 上运行有任何建议吗?

【问题讨论】:

    标签: java android apache https sun


    【解决方案1】:

    你可以试试这个解决方案:

            try 
            {
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet(url);
                HttpResponse response = client.execute(request);
    
                InputStream in = response.getEntity().getContent();
            } 
            catch (Exception e) 
            {
                // Code
            }
    

    暂时不记得正确的异常,但我想你可以找到它。

    【讨论】:

    • 这可能适用于其他情况。但我需要使用 Http basic 进行身份验证。这就是我使用 URLConnection 的原因。不过谢谢你的回复
    • 啊,好的。有一些资源,你可以查看here
    猜你喜欢
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 2012-01-02
    • 2011-05-06
    • 1970-01-01
    • 2011-05-03
    • 2012-01-09
    • 1970-01-01
    相关资源
    最近更新 更多