HttpClient不会导入Android Studio


359

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

package com.mysite.myapp;

import org.apache.http.client.HttpClient;

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

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

Cannot resolve symbol HttpClient

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

有无最后一条编译行,错误是相同的。我想念什么?


4
AndroidHttpClient如果可以,请尝试使用。HttpClient存根确实包含在android jar中,因此无需显式引用它。请注意,httpclient的Android版本可能是4.1.1。尝试在此之上使用较新的版本通常会带来麻烦(请阅读:不起作用,因为固件类加载器始终会胜出)。
dhke

Answers:


813

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

如果需要sdk 23,请将其添加到gradle:

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

你也可以尝试下载并包括HttpClient的罐子直接到你的项目,或者使用OkHttp代替



20
就我而言,它没有任何作用。怎么来的?
Android开发人员

2
添加时,useLibrary无法解析。我的目标是23,我想念的是什么?
Badr 2015年

1
android { useLibrary 'org.apache.http.legacy' } [当您添加此内容时] [1] 'org.apache.http'android-studio仍然有提示:'无法解析符号' [2]这使android-studio(使用sdk23)可以构建。坊间有提示(不能解析符号)[3]如果u加罐子,它没有任何提示,可以建立,但是!!!无法运行,因为它有两个副本“org.apache.http”
YETI

1
对于在那里使用该Volley库的任何人,请注意,此gradle行的添加应放入该库的gradle文件中,而不是您的应用程序中。完美的作品!万分感谢!
sravan953 '16

162

HttpClient在API级别22中已弃用,在API级别23中已删除。如果需要,您仍然可以在API级别23及更高版本中使用它,但是最好移至受支持的方法来处理HTTP。因此,如果您使用23进行编译,请将其添加到build.gradle中:

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

4
android { useLibrary 'org.apache.http.legacy' } [当您添加此内容时] [1] 'org.apache.http'android-studio仍然有提示:'无法解析符号' [2]这使android-studio(使用sdk23)可以构建。坊间有提示(不能解析符号)[3]如果u加罐子,它没有任何提示,可以建立,但是!!!无法运行,因为它有两个副本“org.apache.http”
YETI

1
[2.1]因此,请关闭Android Studio并重新启动,不要打开使用旧版代码的文件,并且不会使用“提示”。如果您需要打开文件,则表明您是该代码的所有者,因此[4]应该停止在您控制的代码中使用HttpClient。
straya 2015年

不知道为什么(build-tool&sdk)23表现得如此怪异。事件不支持开发人员使用“ apche http”。
YETI

1
您必须将android studio更新为最新版本,以避免此行为...它已在新版本中修复
rawcoder064

什么是“支持的HTTP处理方法”?
waldgeist

59

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

谢谢,这是唯一可与新的实验性版本一起使用的解决方案,因为useLibrary无法在其中识别
pt123

实际上,这是比上面的答案更好的答案!它可以与较新版本的编译器一起使用
Matan Dahan

48

要将Apache HTTP用于SDK级别23:

顶级build.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 Studio的有关gradle更新的通知:

来自Android Studio的有关Gradle更新的通知

特定于模块的build.gradle-/app/build.gradle

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

31

试试这个对我有用

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

16

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->项目->应用程序->库

,然后把罐子放在那里。

3-在build.gradle(模块:app)中添加

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

 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;

14

在sdk 23中,不再支持HttpClient。Android6.0(API级别23)版本删除了对Apache HTTP客户端的支持。你必须用

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

并在您的依赖项中添加以下代码片段:

// http的Web服务最终解决方案(包括文件上传)

compile('org.apache.httpcomponents:httpmime:4.3.6') {
        exclude module: 'httpclient'
}
 compile 'org.apache.httpcomponents:httpclient-android:4.3.5'

在使用“使用MultipartEntity进行文件上传”时,它也将为您提供帮助。


很高兴听到它对您有帮助:)
android_sh

我对此有问题...重复的条目:org / apache / http / HttpHeaders.class。你知道是什么问题吗?
DaniG '16

7

在API 22中,它们已被弃用,在API 23中,它们被完全删除,如果您不需要所有新添加的花哨的东西,一个简单的解决方法是仅使用来自API 22之前集成的apache的.jar文件,但是作为单独的.jar文件:

1. http://hc.apache.org/downloads.cgi
2. download httpclient 4.5.1, the zile file
3. unzip all files
4. drag in your project httpclient-4.5.1.jar, httpcore-4.4.3.jar and httpmime-4.5.1.jar
5. project, right click, open module settings, app, dependencies, +, File dependency and add the 3 files
6. now everything should compile properly

7

如果要导入某些类,例如:

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

您可以在build.gradle中添加以下行(Gradle依赖项)

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

    .
    .
    .

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

}

完美的答案!我必须使用wrapped.org.apache,因为我需要更新一个非常老的项目。谢谢。
dianakarenms '18 -10-21

6

您可以简单地将其添加到Gradle依赖项中:

compile "org.apache.httpcomponents:httpcore:4.3.2"

2
这会有所帮助。但是如果您想使用其他类(如)仍然不够HttpGet。为此,我使用了compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
AlexAndro

6

Android 6.0(API级别23)版本删除了对Apache HTTP客户端的支持。因此,您不能直接在API 23中使用此库。但是有一种使用方法。如下所示,在build.gradle文件中添加useLibrary'org.apache.http.legacy'-

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

如果这不起作用,您可以应用以下技巧-

–将android.sdk目录的/ platforms / android-23 /可选路径中的org.apache.http.legacy.jar复制到项目的app / libs文件夹中。

–现在在build.gradle文件的dependencies {}部分中添加编译文件('libs / org.apache.http.legacy.jar')。


您提供的最后一个选项做得很好。我很感激
约瑟夫

5

v23 sdk中已删除ApacheHttp Client。您可以使用HttpURLConnection或OkHttp之类的第三方Http Client。

参考: https://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client


使用HttpUrlConnection中的HttpClient代替实际上是鼓励
本·皮尔逊


4

sdk 23和23+中不支持HttpClient。

如果您需要在sdk 23中使用,请将以下代码添加到gradle中:

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

它为我工作。希望对您有用。


与SDK版本24完美搭配
-Daksh Mehta


4

您只需要添加一行

useLibrary 'org.apache.http.legacy'

例如到build.gradle(Module:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "25.0.0"

    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.avenues.lib.testotpappnew"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'
}

3

您在项目中拥有哪个API目标?AndroidHttpClient仅适用于API级别8 <。请在这里看看

享受你的代码:)


3

如前所述,以下org.apache.http.client.HttpClient内容不再受支持:

SDK(API级别)#23。

您必须使用java.net.HttpURLConnection

如果你想使用时,你的代码(生活)更容易HttpURLConnection,这里是一个Wrapper这个类可以让你做简单的操作GETPOSTPUT使用JSON,例如像做了HTTP PUT

HttpRequest request = new HttpRequest(API_URL + PATH).addHeader("Content-Type", "application/json");
int httpCode = request.put(new JSONObject().toString());
if (HttpURLConnection.HTTP_OK == httpCode) {
    response = request.getJSONObjectResponse();
} else {
  // log error
}
httpRequest.close()

随意使用它。

package com.calculistik.repository;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * <p>
 * Copyright © 2017, Calculistik . All rights reserved.
 * <p>
 * Oracle and Java are registered trademarks of Oracle and/or its
 * affiliates. Other names may be trademarks of their respective owners.
 * <p>
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common
 * Development and Distribution License("CDDL") (collectively, the
 * "License"). You may not use this file except in compliance with the
 * License. You can obtain a copy of the License at
 * https://netbeans.org/cddl-gplv2.html or
 * nbbuild/licenses/CDDL-GPL-2-CP. See the License for the specific
 * language governing permissions and limitations under the License.
 * When distributing the software, include this License Header
 * Notice in each file and include the License file at
 * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this particular file
 * as subject to the "Classpath" exception as provided by Oracle in the
 * GPL Version 2 section of the License file that accompanied this code. If
 * applicable, add the following below the License Header, with the fields
 * enclosed by brackets [] replaced by your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 * <p>
 * Contributor(s):
 * Created by alejandro tkachuk @aletkachuk
 * www.calculistik.com
 */
public class HttpRequest {

    public static enum Method {
        POST, PUT, DELETE, GET;
    }

    private URL url;
    private HttpURLConnection connection;
    private OutputStream outputStream;
    private HashMap<String, String> params = new HashMap<String, String>();

    public HttpRequest(String url) throws IOException {
        this.url = new URL(url);
        connection = (HttpURLConnection) this.url.openConnection();
    }

    public int get() throws IOException {
        return this.send();
    }

    public int post(String data) throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.POST.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        this.sendData(data);
        return this.send();
    }

    public int post() throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.POST.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        return this.send();
    }

    public int put(String data) throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.PUT.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        this.sendData(data);
        return this.send();
    }

    public int put() throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.PUT.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        return this.send();
    }

    public HttpRequest addHeader(String key, String value) {
        connection.setRequestProperty(key, value);
        return this;
    }

    public HttpRequest addParameter(String key, String value) {
        this.params.put(key, value);
        return this;
    }

    public JSONObject getJSONObjectResponse() throws JSONException, IOException {
        return new JSONObject(getStringResponse());
    }

    public JSONArray getJSONArrayResponse() throws JSONException, IOException {
        return new JSONArray(getStringResponse());
    }

    public String getStringResponse() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        for (String line; (line = br.readLine()) != null; ) response.append(line + "\n");
        return response.toString();
    }

    public byte[] getBytesResponse() throws IOException {
        byte[] buffer = new byte[8192];
        InputStream is = connection.getInputStream();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        for (int bytesRead; (bytesRead = is.read(buffer)) >= 0; )
            output.write(buffer, 0, bytesRead);
        return output.toByteArray();
    }

    public void close() {
        if (null != connection)
            connection.disconnect();
    }

    private int send() throws IOException {
        int httpStatusCode = HttpURLConnection.HTTP_BAD_REQUEST;

        if (!this.params.isEmpty()) {
            this.sendData();
        }
        httpStatusCode = connection.getResponseCode();

        return httpStatusCode;
    }

    private void sendData() throws IOException {
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            result.append((result.length() > 0 ? "&" : "") + entry.getKey() + "=" + entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
        }
        sendData(result.toString());
    }

    private HttpRequest sendData(String query) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(query);
        writer.close();
        return this;
    }

}

2

在依赖项下添加这两行

compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'

然后

useLibrary 'org.apache.http.legacy'

在android下


1

另一种方法是,如果您有httpclient.jar文件,则可以执行以下操作:

将您的.jar文件粘贴到项目的“ libs文件夹”中。然后在gradle中将此行添加到build.gradle(Module:app)

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.0.0'
compile files('libs/httpcore-4.3.3.jar')
}

0

错误:(30,0)未找到Gradle DSL方法:“ classpath()”可能的原因:

  • 项目'cid'可能正在使用不包含该方法的Android Gradle插件版本(例如,在1.1.0中添加了'testCompile')。将插件升级到版本2.3.3并同步项目
  • 项目“ cid”可能正在使用不包含该方法的Gradle版本。打开Gradle包装器文件
  • 生成文件可能缺少Gradle插件。应用Gradle插件

  • 0

    对于Android API 28及更高版本(位于应用程序标签中的Manifest.xml中)

        <application
        .
        .
        .
    
        <uses-library android:name="org.apache.http.legacy" android:required="false"/>

    -1

    我认为,取决于您使用的是哪个Android Studio版本,同样重要的是您也要更新android studio,我也受到大家的建议而感到沮丧,但是没有运气,直到我不得不将Android版本从1.3升级到1.5,错误消失了,魔法。

    By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
    Licensed under cc by-sa 3.0 with attribution required.