HttpsURLConnection在android studio

时间:2016-06-02 12:04:35

标签: android httpurlconnection

我正在使用android studio开发一个应用程序,我对android完全陌生,这是我的第二个应用程序,我已经到处寻找一种方法来打开一个URL并阅读Json的内容来自它,这些是我找到的代码,但问题是它到达的地方" con.connect();"它说不幸的是你的应用程序已停止工作我甚至无法读取该网址中的字符串,我真的不知道问题是什么,所以我希望你能帮我解决这个问题。

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 "";
}

顺便说一句,我已经获得了android清单中的互联网权限。 谢谢你的帮助。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:-3)

添加useLibrary' org.apache.http.legacy'在android部分的app build.gradle中。

如下图所示:

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'
    }