HttpClient не будет импортироваться в Android Studio

У меня есть простой класс, написанный в 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

Не входит ли 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'
}

С последней линией компиляции или без нее ошибка будет такой же. Что мне не хватает?

Ответ 1

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 jar прямо в свой проект или использовать OkHttp вместо

Ответ 2

HttpClient устарел на уровне API 22 и удалился в API-уровне 23. Вы все равно можете использовать его в API-интерфейсе 23 и далее, если вам нужно, однако лучше всего перейти к поддерживаемым методам обработки HTTP. Итак, если вы компилируете с 23, добавьте это в свой build.gradle:

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

Ответ 4

Использовать 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 о gradle обновлении:

Уведомление от студии Android о  gradle update

Специфичный для модуля build.gradle -/app/build.gradle

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

Ответ 5

Попробуйте это работал на меня Добавьте эту зависимость в файл build.gradle

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

Ответ 6

1- загрузка файлов jar Apache (с этого ответа) 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- В build.grale(Mudule: 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;

Ответ 7

HttpClient больше не поддерживается в sdk 23. Релиз Android 6.0 (API Level 23) удаляет поддержку для HTTP-клиента Apache. Вы должны использовать

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

а также добавить ниже фрагмент кода в вашей зависимости:

//http окончательное решение для веб-сервиса (включая загрузку файлов)

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

Это также поможет вам, когда вы используете Use MultipartEntity для Загрузка файла.

Ответ 8

в API 22 они устаревают, а в API 23 они полностью их удалили, простое обходное решение, если вам не нужны все причудливые вещи из новых дополнений, - просто использовать файлы .jar из apache, которые были интегрированы перед API 22, но в виде отдельных файлов .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

Ответ 9

Клиент ApacheHttp удален в v23 sdk. Вы можете использовать HttpURLConnection или сторонний Http-клиент, например OkHttp.

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

Ответ 10

В выпуске Android 6.0 (API Level 23) удаляется поддержка HTTP-клиента Apache. Следовательно, вы не можете использовать эту библиотеку непосредственно в API 23. Но есть способ ее использования. Добавить useLibrary 'org.apache.http.legacy в файле build.gradle, как показано ниже -

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

Если это не сработает, вы можете применить следующий хак -

- Скопируйте org.apache.http.legacy.jar, который находится в каталоге /platform/android -23/optional вашего каталога Android SDK в папку приложений /libs проектов.

- Теперь добавьте компилируемые файлы ('libs/org.apache.http.legacy.jar) внутри зависимых {} разделов файла build.gradle.

Ответ 11

Вы можете просто добавить это в зависимости от Gradle:

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

Ответ 12

Просто используйте это: -

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

Ответ 13

HttpClient не поддерживается в sdk 23 и 23 +.

Если вам нужно использовать в sdk 23, добавьте ниже код в свой gradle:

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

Он работает для меня. Надеюсь, полезно для вас.

Ответ 14

Какой целевой API вы используете в своем проекте? AndroidHttpClient предназначен только для уровня API 8. и пожалуйста, посмотрите здесь

наслаждайтесь кодом:)

Ответ 15

Если вам нужен sdk 23, добавьте его в свой gradle:

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

Ответ 16

Другой способ - если у вас есть 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')
}

Ответ 17

Добавьте эти две строки под зависимостями

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

то

useLibrary 'org.apache.http.legacy'

под андроидом

Ответ 18

Вам нужно добавить только одну строку

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

Ответ 19

Как уже упоминалось ранее, org.apache.http.client.HttpClient больше не поддерживается:

SDK (уровень API) # 23.

Вы должны использовать java.net.HttpURLConnection.

Если вы хотите сделать свой код (и жизнь) проще при использовании HttpURLConnection, вот Wrapper этого класса, который позволит вам выполнять простые операции с GET, POST и PUT, используя 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;
    }

}

Ответ 20

Ошибка: (30, 0) Gradle Метод DSL не найден: 'classpath()' Возможные причины:

В проекте "cid" может использоваться версия плагина Android Gradle, который не содержит метода (например, "testCompile" был добавлен в 1.1.0). Обновление плагина до версии 2.3.3 и проекта синхронизации В проекте "cid" может использоваться версия Gradle, которая не содержит этот метод. Откройте файл оболочки Gradle В файле сборки может отсутствовать плагин Gradle. Примените плагин Gradle

Ответ 21

Я думаю, в зависимости от того, какая версия Android Studio у вас есть, важно также обновить свою студию Android, я тоже разочаровался в каждом совете, но не повезло, пока мне не пришлось обновлять версию Android от 1.3 до 1.5, ошибки исчезли, как магия.