2015-02-07 72 views
0

我想从url中获取数据,它显示为空。Android - 从URL问题获取数据

这里是我的代码

   try { 
       URL urlA = new URL("http://www.domain.com/work123.html"); 
       BufferedReader in = new BufferedReader(new InputStreamReader(urlA.openStream())); 

       String inputLineA; 

       while ((inputLineA = in.readLine()) != null) 
        htmlCodeA += inputLineA; 

       in.close(); 
       } catch (Exception e) { 

        //Log.d(LOG_TAG, "Error: " + e.toString()); 
       }   

请让我知道我在做什么错误。

问候,

+0

捕获异常是不是一个很好的工作,也许您尝试在UI线程连接互联网或者您没有设置权限,尝试后异常错误 – 2015-02-07 09:30:24

回答

-1
URL connectURL = new URL(urlstring); 

     HttpURLConnection hc = (HttpURLConnection) connectURL.openConnection(); 

hc.setConnectTimeout(20 * 1000);

   Enumeration kyes = header.keys(); 
       while (kyes.hasMoreElements()) { 
        String key = (String) kyes.nextElement(); 
        String value = (String) header.get(key); 
        hc.setRequestProperty(key, value); 
       } 

InputStream is = hc.getInputStream();

   resMessage = new String(readFully(is), "UTF-8") 


public static byte[] readFully(InputStream input) throws IOException 
{ 
    byte[] buffer = new byte[Constants.BUFFER_SIZE]; 
    int bytesRead; 
    ByteArrayOutputStream output = new ByteArrayOutputStream(); 
    while ((bytesRead = input.read(buffer)) != -1) 
    { 
     output.write(buffer, 0, bytesRead); 
    } 
    return output.toByteArray(); 
} 
+0

'的System.gc()'???真??? – 2015-02-07 09:59:58

0

既然你在Android栏目发帖,它几乎可以保证,你将要在AsyncTask运行这个,而不是与的AsyncTask阻止UIThread。没有任何错误处理程序

String htmlCodeA = ""; 
// 
// A bunch of lines later... 
try{ 
    HttpClient client = new DefaultHttpClient(); 
    HttpPost request = new HttpPost("http://www.domain.com/work123.html"); 
    HttpResponse response = client.execute(request); 
    InputStreamReader isr = new InputStreamReader(response.getEntity().getContent()); 
    BufferedReader reader = new BufferedReader(isr); 
    String line = ""; 
    while((line = reader.readLine())!=null) 
    { 
    htmlCodeA += line; 
    } 
} 
catch(MalformedURLException e) { /* Do whatever you want here. */} 
catch(IOException e) { /* Do whatever you want here. */}