Android Studio中无法导入HttpClient

384

我有一个在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 build中:

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。Android版的HttpClient存根确实包含在android jar中,因此通常不需要明确引用它。请注意,android版的httpclient可能是4.1.1版本。试图在其基础上使用更新版本通常会导致问题(即:无法工作,因为固件类加载器始终获胜)。 - dhke
重复 https://dev59.com/a1wY5IYBdhLWcg3w2Kwv#32157466. - straya
25个回答

6

Android 6.0 (API Level 23)发布后,不再支持Apache HTTP客户端。因此,您无法在API 23中直接使用此库。但是有一种方法可以使用它。请按照以下步骤在build.gradle文件中添加useLibrary 'org.apache.http.legacy' -

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

如果这个方法不起作用,你可以尝试以下hack方法: - 在Android SDK目录下的/platforms/android-23/optional路径中复制org.apache.http.legacy.jar文件到项目的app/libs文件夹中。 - 现在,在build.gradle文件的dependencies{}部分添加compile files('libs/org.apache.http.legacy.jar')。

你给出的最后一个选项很好地完成了任务。我很感激。 - Joseph

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

5

在v23 sdk中,ApacheHttp客户端已被删除。您可以使用HttpURLConnection或第三方Http客户端,如OkHttp。

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


使用 HttpUrlConnection 而不是 HttpClient 是被鼓励的。 - Ben Pearson

5

您只需要添加一行代码

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

4

如前所述,org.apache.http.client.HttpClient不再支持以下版本的SDK(API级别)#23。

您必须使用java.net.HttpURLConnection

如果您想在使用HttpURLConnection时使代码(和生活)更轻松,请使用此类的Wrapper,它将让您使用JSON执行简单的GETPOSTPUT操作,例如执行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;
    }

}

4

HttpClient在sdk 23和23+中不受支持。

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

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

对我来说它有效。希望对你有用。


与SDK版本24完美配合。 - Daksh Mehta

4
如果你需要 SDK 23,可以将以下代码添加到你的 gradle 文件中:
android {
    useLibrary 'org.apache.http.legacy'
}

4
只需要使用以下代码:
android {
         .
         .
         .
 useLibrary 'org.apache.http.legacy'
         .
         .
         .
          }

3

您的项目中使用了哪个API目标?AndroidHttpClient仅适用于API Level 8 <。请查看此处

愉快编码 :)


2
另一种方法是如果您有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')
}

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