2011-11-26 103 views
0

我的Android http url连接有问题。 我有这样的方法:当我使用它从一个普通的Java应用程序Android http基本认证

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

它工作得很好。 但是,当我从Android应用程序运行它不起作用。

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

在正常的Java应用程序中,它使用sun.net ... HttpURLConnection(它的工作原理)。

任何人有任何建议,我怎么能得到这个在Android上工作?

回答

-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 
     } 

不记得此刻的正确例外,但我认为你可以找到它。

+0

这可能适用于其他情况。但我需要使用Http basic进行身份验证。这就是我使用URLConnection的原因。但是,谢谢你的回复 – user1066441

+0

啊,好的。有一些资源,你可以检查[这里](http://hc.apache.org/httpcomponents-client-ga/examples.html)。 – iCantSeeSharp