Android Studio无法解析符号'HttpClient'。

4

我有一个Android项目,需要使用http请求。

我使用以下简单代码:

public void onGetClick(View v) {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://www.google.com");
    HttpResponse response = client.execute(request);

    BufferedReader rd = new BufferedReader(new InputStreamReader
(response.getEntity().getContent()));

    String line = "";
    while ((line = rd.readLine()) != null) {
        Log.d("WM.ALS", line);
    }

}

但是我找不到HttpClient库。

我将从Apache (http://hc.apache.org/downloads.cgi) 下载的.jar文件添加到了/lib目录中,并在 "build.gradle(Module: app)" 文件中添加了以下内容:

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  testCompile 'junit:junit:4.12'
  compile 'com.android.support:appcompat-v7:23.1.1'

  compile 'com.android.support:design:23.0.1'
  compile 'org.apache.httpcomponents:httpcore-4.4.3'
  compile 'org.apache.httpcomponents:httpclient-4.5.1'

但是仍然没有效果...

我该怎么办?


为什么不使用 HttpURLConnection - Dhaval Patel
我没有考虑过它。 - img.simone
为什么在HttpURLConnection提供相同功能时要使用额外的(已弃用)库? - Dhaval Patel
3个回答

10
在build.gradle(Module:app)中添加以下内容。
android {
    useLibrary 'org.apache.http.legacy'
}

它正在工作。


4
您正在使用appcompat-v7:23.1.1'。在此处已弃用HttpClient

SDK 23不支持HttpClient。您需要使用URLConnection

一个URLConnection用于HTTP(RFC 2616),用于在Web上发送和接收数据。数据可以是任何类型和长度。该类可用于发送和接收长度未知的流数据。

请检查HttpClient won't import in Android Studio

您可以使用org.apache.http.legacy

Android 6.0版本删除了对Apache HTTP客户端的支持。如果您的应用程序正在使用此客户端并针对Android 2.3(API级别9)或更高版本,请改用HttpURLConnection类。此API更有效,因为它通过透明压缩和响应缓存减少了网络使用,并最小化了功耗。要继续使用Apache HTTP API,您必须首先在build.gradle文件中声明以下编译时依赖项。

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

然后进行“清理-重建-同步”。希望这可以帮到你。

https://dev59.com/qJPfa4cB1Zd3GeqPD3w1?answertab=active#tab-top - IntelliJ Amiya

2

如@Rushabh042所回答的:

    android{
            compileSdkVersion 23
            buildToolsVersion "23.0.2"
            useLibrary 'org.apache.http.legacy'
           }

将会完美运作! 或者你也可以这样操作:

Android Studio->文件->项目结构->(在左侧Modules部分选择您的应用程序)依赖项选项卡->添加依赖项

搜索org.apache.http.legacy并从搜索列表中进行选择。

重新构建您的应用程序,然后就可以了...:)

编程愉快!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接