2014-03-04 2 views
0

내 Android 앱에서 웹 페이지 콘텐츠를 가져 오는 데 문제가 있습니다. 나는이 주소 https://szr.szczecin.pl/utms/data/layers/VMSPublic에서 내용을 읽고 싶다. 안드로이드에서 웹 페이지 콘텐츠를 얻는 방법?

는 처음에 나는이 코드를 사용하여 Java에서 그것을 할 시도 : I 다운로드 및 해당 웹 페이지에서 인증서를 설치 한 후 근무

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에서 어떻게 똑같이 할 수 있습니까? 안드로이드에서 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

모두 사용 중지되었습니다. –

2

당신이 모든 네트워크 관련 작업에 대한 아파치 HttpClient를를 사용하는 앱에서 23로 대상 SDK를 설정하려고합니까? 그렇다면 나쁜 소식이 있습니다. Android 6.0 (API 레벨 23) 릴리스에서는 Apache HTTP 클라이언트에 대한 지원이 제거되었습니다. 따라서 API 23에서이 라이브러리를 직접 사용할 수는 없습니다. 그러나이를 사용하는 방법이 있습니다. 복사 org.apache.http -이 다음 hack-

을 적용 할 수 있습니다 작동하지 않는 경우 below-

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

로 build.gradle 파일에 useLibrary 'org.apache.http.legacy을'추가 .legacy.jar는/platforms/android-23/안드로이드 SDK 디렉토리의 경로를 프로젝트의 app/libs 폴더에 저장합니다.

- 이제 build.gradle 파일의 종속성 {} 섹션에 컴파일 파일 ('libs/org.apache.http.legacy.jar')을 추가하십시오.

관련 문제