2016-06-02 6 views
0

저는 android studio를 사용하여 응용 프로그램을 개발하고 있습니다. 저는 Android에 완전히 익숙하지 않습니다. 이것은 두 번째 응용 프로그램입니다. URL을 열고 그것에서 Json 콘텐츠를 읽으십시오, 이것들은 제가 발견 한 코드입니다. 그러나 문제는 "con.connect();"에 도착하는 곳입니다. 불행히도 귀하의 응용 프로그램이 작동하지 않는다고 말합니다. 그 URL의 문자열도 읽을 수 없으며, 정말 문제가 무엇인지 모르므로이 문제를 해결할 수 있도록 도와주세요.HttpsURLConnection이 android studio에서 작동하지 않습니다.

public String webrequest(String url1){ 
    try { 

     URL url = new URL(url1); 
     HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); 
     con.connect(); 
     if (con != null) { 
      try { 
       BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8")); 
       String input; 
       while ((input = br.readLine()) != null) { 
       System.out.println(input); 
       } 
       br.close(); 
       return input.toString(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    //return input; 
    return ""; 
} 

그리고 그런데, 나는 안드로이드 매니페스트에서 인터넷 허가를 받았습니다. 도움 주셔서 감사합니다.

+1

하면 주 (UI) 스레드 외부에서이 코드를 실행 했습니까? AsyncTask 또는 유사한 스레드 지향 접근 방식을 사용 했습니까? – devnull69

답변

-3

android 섹션의 app build.gradle에서 useLibrary 'org.apache.http.legacy'를 추가하십시오.

아래와 같이

android { 
     compileSdkVersion 23 
     buildToolsVersion "23.0.2" 

     defaultConfig { 
      applicationId "com.test.smapp" 
      minSdkVersion 14 
      targetSdkVersion 23 
     } 
     packagingOptions { 
      exclude 'META-INF/NOTICE.txt' 
     } 

     buildTypes { 
      release { 
       minifyEnabled false 
       proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' 
      } 
     } 
     useLibrary 'org.apache.http.legacy' 
    } 
+0

OP는 HttpsURLConnection을 사용하려고합니다. 이러한 의도를 존중 해주세요. –

1

이 편대 시도 -

private InputStream openHttpConnection(String urlStr) { 
    InputStream in = null; 
    int resCode = -1; 

    try { 
    URL url = new URL(urlStr); 
    URLConnection urlConn = url.openConnection(); 

    if (!(urlConn instanceof HttpURLConnection)) { 
     throw new IOException("URL is not an Http URL"); 
    } 
    HttpURLConnection httpConn = (HttpURLConnection) urlConn; 
    httpConn.setAllowUserInteraction(false); 
    httpConn.setInstanceFollowRedirects(true); 
    httpConn.setRequestMethod("GET"); 
    httpConn.connect(); 
    resCode = httpConn.getResponseCode(); 

    if (resCode == HttpURLConnection.HTTP_OK) { 
     in = httpConn.getInputStream(); 
    } 
    } 

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

    catch (IOException e) { 
    e.printStackTrace(); 
    } 
    return in; 
} 
+0

'HttpsURLConnection'은 어떻게됩니까? –

관련 문제