Android - Send HTTP Request (API > 23)



我需要一些"下载"网页内容的东西......我的意思是,我需要有HTTP响应并将其存储到字符串变量中。

例如,如果我插入 www.example.com,响应将如下所示:<html><head></head><body>THIS IS AN EXAMPLE etc etc etc...<><><>

尝试了一些我看到的代码,但它们来自API <23,Android已经删除了HTTP APACHE。

提前感谢你

HttpUrlConnection 是 apache 库的替代品。

您可以添加

 useLibrary 'org.apache.http.legacy'

在 gradle 文件中,您可以在 API 23 + 中使用 HTTP Apache 类。

您有两个选择:1- 使用 Android URL 用于 EX:

 URL url = new URL("http://www.example.com");
   URLConnection urlConnection = url.openConnection();
   InputStream in = new BufferedInputStream(urlConnection.getInputStream());
   try {
     readStream(in);
    finally {
     in.close();
   }
 }

2-将以下内容添加到您的gradle文件中

 useLibrary 'org.apache.http.legacy'

另一种选择是使用 OKHttp 库。

将此添加到您的 gradle 文件中:

编译 'com.squareup.okhttp3:okhttp:3.2.0'

该库使用起来相对简单:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
      .url(url)
      .build();
Response response = client.newCall(request).execute();
String body = response.body().string();

最新更新