2013-05-22 6 views
1

Мне нужна помощь; Мне действительно нужно прочитать и использовать содержимое какого-либо веб-сайта в приложении для Android. Я следовал за некоторыми учебниками, но напрасно. Кто-то может помочь мне здесь.как читать и использовать содержимое веб-сайта в android

Обновлено:

Я на самом деле использовали два различных кода, чтобы получить содержимое веб-сайта, но они не работали для меня

public static String connect(String url) 
{ 
    String result = "bubububu" ; 

    HttpClient httpclient = new DefaultHttpClient(); 

    // Prepare a request object 
    HttpGet httpget = new HttpGet(url); 

    // Execute the request 
    HttpResponse response; 
    try { 
     response = httpclient.execute(httpget); 
     // Examine the response status 
     Log.i("Praeda",response.getStatusLine().toString()); 

     // Get hold of the response entity 
     HttpEntity entity = response.getEntity(); 
     // If the response does not enclose an entity, there is no need 
     // to worry about connection release 

     if (entity != null) { 

      // A Simple JSON Response Read 
      InputStream instream = entity.getContent(); 
      result= convertStreamToString(instream); 
      // now you have the string representation of the HTML request 
      instream.close(); 
      return result ; 
     } 


    } catch (Exception e) { 
     e.getMessage() ; 
    } 

    return result ; 
} 

    private static String convertStreamToString(InputStream is) { 
    /* 
    * To convert the InputStream to String we use the BufferedReader.readLine() 
    * method. We iterate until the BufferedReader return null which means 
    * there's no more data to read. Each line will appended to a StringBuilder 
    * and returned as String. 
    */ 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 


public static String connect(String url) 
{ 
    String result = "bubububu" ; 

    HttpClient httpclient = new DefaultHttpClient(); 

    // Prepare a request object 
    HttpGet httpget = new HttpGet(url); 

    // Execute the request 
    HttpResponse response; 
    try { 
     response = httpclient.execute(httpget); 
     // Examine the response status 
     Log.i("Praeda",response.getStatusLine().toString()); 

     // Get hold of the response entity 
     HttpEntity entity = response.getEntity(); 
     // If the response does not enclose an entity, there is no need 
     // to worry about connection release 

     if (entity != null) { 

      // A Simple JSON Response Read 
      InputStream instream = entity.getContent(); 
      result= convertStreamToString(instream); 
      // now you have the string representation of the HTML request 
      instream.close(); 
      return result ; 
     } 


    } catch (Exception e) { 
     e.getMessage() ; 
    } 

    return result ; 
} 

    private static String convertStreamToString(InputStream is) { 
    /* 
    * To convert the InputStream to String we use the BufferedReader.readLine() 
    * method. We iterate until the BufferedReader return null which means 
    * there's no more data to read. Each line will appended to a StringBuilder 
    * and returned as String. 
    */ 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 

И

private String DownloadText(String URL) 
{ 
    int BUFFER_SIZE = 2000; 
    InputStream in = null; 
    try { 
     in = OpenHttpConnection(URL); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
     return ""; 
    } 

    InputStreamReader isr = new InputStreamReader(in); 
    int charRead; 
    String str = ""; 
    char[] inputBuffer = new char[BUFFER_SIZE];   
    try { 
     while ((charRead = isr.read(inputBuffer))>0) 
     {      
      //---convert the chars to a String--- 
      String readString = String.copyValueOf(inputBuffer, 0, charRead); 
      str += readString; 
      inputBuffer = new char[BUFFER_SIZE]; 
     } 
     in.close(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     return ""; 
    }  
    return str;   
} 

private InputStream OpenHttpConnection(String urlString) 
     throws IOException 
     { 
    InputStream in = null; 
    int response = -1; 

    URL url = new URL(urlString); 
    URLConnection conn = url.openConnection(); 

    if (!(conn instanceof HttpURLConnection))      
     throw new IOException("Not an HTTP connection"); 

    try{ 
     HttpURLConnection httpConn = (HttpURLConnection) conn; 
     httpConn.setAllowUserInteraction(false); 
     httpConn.setInstanceFollowRedirects(true); 
     httpConn.setRequestMethod("GET"); 
     httpConn.connect(); 

     response = httpConn.getResponseCode();     
     if (response == HttpURLConnection.HTTP_OK) { 
      in = httpConn.getInputStream();         
     }      
    } 
    catch (Exception ex) 
    { 
     throw new IOException("Error connecting");    
    } 
    return in;  
     } 

Оба это дает мне исключение. первого один дает исключение в ответ = httpclient.execute (HttpGet) и exception.getMessage() является «нулевым» в то время как вторым один дает исключение в httpConn.setAllowUserInteraction (ложь) и exception.getMessage() является ошибкой подключения. Даже я использовал разрешение Интернет в menifest файла

+0

Возможно, вам придется быть более конкретным в вопросе, но я все равно займу ответ –

+0

Если вам не разрешено получать веб-сервис от веб-мастера, это не очень хорошая идея! –

+0

спасибо другу; что вы, люди, хотите быть более конкретными здесь. У меня есть только эти данные, то есть URL-адрес веб-сайта, получение определенного контента отсюда и использование этого контента в моем приложении. – user2281330

ответ

0

Посмотрите ответ на этот вопрос: How do I use the Simple HTTP client in Android?

Он имеет код, который будет читать некоторые URL.

Однако, это хорошая идея быть более конкретным в StackOverflow и объяснить, что именно ваша проблема.

0

Не на 100% уверены в вопросе, но вы можете использовать Apache HTTPClient (рекомендуется для pre-Gingerbread) или HTTPURLConnection (Gingerbread и далее) и выполнить GET для получения веб-страницы. Отсюда вы можете просмотреть необработанные данные (обычно HTML, который возвращается в виде текста). В настоящее время есть много хороших учебников по HTTPClient и HTTPURLConnection, поэтому я не буду здесь объяснять это.

Другой вариант, как правило, WebView, который, я признаю, может быть грязным. WebView позволяет вам входить в систему и делать такие вещи, как извлечение результирующего URL со следующей страницы. Проблема в том, что поведение WebView на устройствах Android не одинаково.

+1

означает webView не является хорошим вариантом, .. спасибо – user2281330

 Смежные вопросы

  • Нет связанных вопросов^_^