我有一个简单的类写在Android Studio:

package com.mysite.myapp;

import org.apache.http.client.HttpClient;

public class Whatever {
    public void headBangingAgainstTheWallExample () {
        HttpClient client = new DefaultHttpClient();
    }
}

从这里我得到了以下编译时错误:

无法解析HttpClient符号

HttpClient不是包含在Android Studio SDK中吗?即使不是,我也像这样把它添加到我的Gradle构建中:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'org.apache.httpcomponents:httpclient:4.5'
}

不管有没有最后一个编译行,错误都是一样的。我错过了什么?


当前回答

TejaDroid的答案在下面的链接中帮助了我。不能在Android Studio导入org.apache.http.HttpResponse

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

    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    ...
}

其他回答

在SDK级别23中使用Apache HTTP:

顶层构建。Gradle - /build.gradle

buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0' 
        // Lowest version for useLibrary is 1.3.0
        // Android Studio will notify you about the latest stable version
        // See all versions: http://jcenter.bintray.com/com/android/tools/build/gradle/
    }
    ...
}

Android工作室关于gradle更新的通知:

特定于模块的构建。Gradle - /app/build.gradle

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

在sdk 23中不再支持HttpClient。你必须使用URLConnection或降级到sdk 22(编译'com.android.support:appcompat-v7:22.2.0')

如果你需要sdk 23,把这个添加到你的gradle:

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

你也可以尝试下载并将HttpClient jar直接包含到你的项目中,或者使用OkHttp代替

1-下载Apache jar文件(从这个答案开始)4.5.zip文件: https://hc.apache.org/downloads.cgi?Preferred=http%3A%2F%2Fapache.arvixe.com%2F

2-打开zip复制jar文件到你的libs文件夹。你可以在你的项目顶部找到它,上面写着“Android”,当你点击它的时候,你会发现一个列表。所以,

Android ->项目->应用程序-> libs

,然后把罐子放在那里。

3-建造中。gradle(模块:app

compile fileTree(dir: 'libs', include: ['*.jar'])

in

 dependency { 
   }

4-在java类中添加这些导入:

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.params.CoreProtocolPNames;

HttpClient在API Level 22中已弃用,并在API Level 23中被移除。如果你必须,你仍然可以在API级别23及以上使用它,但是最好转移到受支持的方法来处理HTTP。所以,如果你用23编译,在build.gradle中添加这个:

android {
    useLibrary("org.apache.http.legacy")
}

TejaDroid的答案在下面的链接中帮助了我。不能在Android Studio导入org.apache.http.HttpResponse

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

    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    ...
}