2014-03-04 34 views
0

我有一個問題,我的Android應用程序中獲取網頁內容。我想閱讀這個地址https://szr.szczecin.pl/utms/data/layers/VMSPublic的內容。如何在Android中獲取網頁內容?

起初,我嘗試使用此代碼來做到這一點在Java中:

public class Main { 

    public static void main(String[] args) { 

     String https_url = "https://szr.szczecin.pl/utms/data/layers/VMSPublic"; 
     URL url; 
     try { 

      url = new URL(https_url); 
      HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); 
      print_content(con); 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    private static void print_content(HttpsURLConnection con) { 
     if (con != null) { 

      try { 

       System.out.println("****** Content of the URL ********"); 
       BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); 

       String input; 

       while ((input = br.readLine()) != null) { 
        System.out.println(input); 
       } 
       br.close(); 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

     } 

    } 

} 

它的工作後,我下載並安裝從該網頁上的證書。我如何在Android中做同樣的事情?我在Android中嘗試了HTTPSURLConnection,但它僅返回了我的網頁地址。當我嘗試使用HTTPURLConnection時,它給了我一個文檔被移動的信息(狀態302)。

回答

2

你可以試試下面的代碼:

public static String getResponseFromUrl(String url) { 
     HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client 
     HttpGet httpget = new HttpGet(URL); // Set the action you want to do 
     HttpResponse response = httpclient.execute(httpget); // Executeit 
     HttpEntity entity = response.getEntity(); 
     InputStream is = entity.getContent(); // Create an InputStream with the response 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) 
      sb.append(line); 

     String resString = sb.toString(); 

     is.close(); 
     return resString; 
     } 
+0

請記住,此功能無法在主線程上運行,否則會導致錯誤。將它放在一個擴展線程的類中或作爲異步 - 可以在這裏找到兩者的示例:http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – RelicScoth

+4

all deprecated ... –

2

你們是不是要設定目標SDK在您的應用程序23這是使用Apache的HttpClient所有網絡相關的操作?如果是的話,這是一個壞消息。 Android 6.0(API Level 23)版本取消了對Apache HTTP客戶端的支持。因此,你不能直接在API 23中使用這個庫。但是有一種方法可以使用它。在您的build.gradle文件中添加useLibrary「org.apache.http.legacy」爲如下─

android { 
    useLibrary 'org.apache.http.legacy' 
} 

如果這不起作用,你可以運用下列hack-

- 複製org.apache.http .legacy.jar,它位於Android SDK目錄的/ platforms/android-23 /可選路徑中,位於項目的app/libs文件夾中。

- 現在在build.gradle文件的依賴關係{}部分中添加編譯文件('libs/org.apache.http.legacy.jar')。