HttpClient nie zaimportuje w Android Studio

Mam prostą klasę napisaną w Android Studio:

package com.mysite.myapp;

import org.apache.http.client.HttpClient;

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

I z tego otrzymuję następujący błąd czasu kompilacji:

Cannot resolve symbol HttpClient

Czy HttpClient nie jest zawarte w Android Studio SDK? Nawet jeśli nie jest, dodałem go do mojego Gradle build w ten sposób:

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

Z ostatnią linią kompilacji lub bez niej, błąd jest taki sam. Co przegapiłem?

Author: Zoe, 2015-08-22

23 answers

HttpClient nie jest już wspierany w sdk 23. Musisz użyć URLConnection lub downgrade do sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')

Jeśli potrzebujesz sdk 23, dodaj to do swojego gradle:

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

Możesz również spróbować pobrać i dołączyć HttpClient jar bezpośrednio do swojego projektu lub użyć OkHttp zamiast

 822
Author: Ilya Blokh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-07 09:39:01

HttpClient został przestarzały w API na poziomie 22 i usunięty w API na poziomie 23. Nadal możesz go używać w API na poziomie 23 i nowszym, jeśli musisz, jednak najlepiej jest przejść do obsługiwanych metod, aby obsłużyć HTTP. Jeśli więc kompilujesz z 23, dodaj to do swojej kompilacji."gradle": {]}

android {
    useLibrary 'org.apache.http.legacy'
}
 163
Author: straya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-22 14:52:22

ODPOWIEDŹ Tejadroida w poniższym linku mi pomogła . nie można importować org.Apacz.http.HttpResponse w Android Studio

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'
    ...
}
 62
Author: Vinay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:37

Aby użyć Apache HTTP dla SDK poziomu 23:

Najwyższy poziom budowy.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/
    }
    ...
}

Powiadomienie od Android studio o aktualizacji gradle:

Powiadomienie z Android studio o aktualizacji gradle

Budowa specyficzna dla modułu.gradle - / app / build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}
 48
Author: AndreyICE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-11 10:54:52

Spróbuj tego / align = "left" / Dodaj tę zależność do swojej kompilacji.gradle File

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
 31
Author: Pritish Joshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-03 09:01:25

1-Pobierz pliki Apache jar (od tej odpowiedzi) 4.5.plik zip from:
https://hc.apache.org/downloads.cgi?Preferred=http%3A%2F%2Fapache.arvixe.com%2F

2-Otwórz plik zip skopiuj pliki jar do folderu libs. Możesz go znaleźć, jeśli przejdziesz na górę projektu, gdzie jest napisane "Android", znajdziesz listę po kliknięciu. Więc

Android -> Project -> app - > libs

,Następnie umieścić słoiki tam.

3 - w budowie.gradle (moduł: aplikacja) dodaj

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

W

 dependency { 
   }

4-w klasie java dodaj ten IMPORT:

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;
 16
Author: fullmoon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-22 19:23:12

HttpClient nie jest już obsługiwany w sdk 23. Android 6.0 (API Level 23) Wersja usuwa obsługę klienta HTTP Apache. Musisz użyć

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

A także dodaj poniższy fragment kodu w zależności:

//http ostateczne rozwiązanie dla web-service (w tym przesyłanie plików)

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

Pomoże Ci również podczas korzystania z Use MultipartEntity doprzesyłania plików .

 15
Author: android_sh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-18 08:03:02

W API 22 stają się przestarzałe, a w API 23 całkowicie je usunęli, prostym obejściem, jeśli nie potrzebujesz wszystkich fantazyjnych rzeczy z nowych dodatków, jest po prostu użycie .pliki JAR z apache, które były zintegrowane przed API 22, ale jako oddzielone .pliki 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
Author: Catalin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-17 17:34:30

Jeśli chcesz zaimportować jakąś klasę jak:

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;

Możesz dodać następującą linię w kompilacji.gradle (Gradle dependencies)

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'

}
 7
Author: A.Bahrami,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-29 17:12:42

Możesz po prostu dodać to do Gradle dependencies:

compile "org.apache.httpcomponents:httpcore:4.3.2"
 6
Author: Mostafa Abdellateef,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-28 12:38:40

Android 6.0 (API Level 23) Wersja usuwa obsługę klienta HTTP Apache. Dlatego nie można używać tej biblioteki bezpośrednio w API 23. Ale jest sposób, aby go użyć. Dodaj useLibrary ' org.Apacz.http.dziedzictwo w Twojej budowie.plik gradle jak poniżej -

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

Jeśli to nie zadziała, możesz zastosować następujący hack -

– Copy org.Apacz.http.dziedzictwo.jar, który znajduje się w /platforms/android-23/opcjonalna ścieżka katalogu Android SDK do folderu app/libs twojego projektu.

– Teraz Dodaj pliki kompilacji ('libs / org.Apacz.http.dziedzictwo.jar') wewnątrz sekcji dependencies{} w build.plik gradle.

 6
Author: user3766643,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-24 02:40:53

Jest to bardzo ważne dla osób, które chcą się z nami skontaktować. Możesz użyć HttpURLConnection lub klienta Http innej firmy, takiego jak OkHttp.

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

 5
Author: Kirtan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-22 07:18:41

Po prostu użyj tego:-

android {
         .
         .
         .
 useLibrary 'org.apache.http.legacy'
         .
         .
         .
          }
 4
Author: Kaushal Kishor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-29 12:49:48

HttpClient nie jest obsługiwany w sdk 23 i 23+.

Jeśli chcesz użyć do sdk 23, dodaj poniższy kod do swojego gradle:

android {
    useLibrary 'org.apache.http.legacy'
}
Działa na mnie. Nadzieja przydatna dla Ciebie.
 4
Author: Sneha Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-11 10:05:36

Jeśli potrzebujesz sdk 23, dodaj to do swojego gradle:

android {
    useLibrary 'org.apache.http.legacy'
}
 4
Author: Shiv Buyya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-12 06:56:19

Musisz dodać tylko jedną linijkę

useLibrary 'org.apache.http.legacy'

Do budowy.gradle(Module: app), na przykład

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
Author: Nilesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-03 11:17:51

Jaki cel API masz w swoim projekcie?AndroidHttpClientjest tylko dla poziomu API 8 <.> Tutaj

Enjoy your code:)

 3
Author: John smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-22 07:14:49

Jak wspomniano wcześniej, org.apache.http.client.HttpClient nie jest już wspierane w:

SDK (poziom API) #23.

Musisz użyć java.net.HttpURLConnection.

Jeśli chcesz, aby Twój kod (i życie) były łatwiejsze podczas używania HttpURLConnection, Oto Wrapper tej klasy, która pozwoli Ci wykonywać proste operacje z GET, POST i PUT używając JSON, np. wykonując 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()

Możesz go użyć.

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

}
 3
Author: Alejandro Pablo Tkachuk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-08 17:30:24

Dodaj te dwie linie w zależności

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

Then

useLibrary 'org.apache.http.legacy'

Pod Androidem

 2
Author: Ramindu Rusara Senarath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-19 05:35:52

Innym sposobem jest posiadanie httpclient.Jar Plik wtedy możesz zrobić to:

Wklej swoje .plik jar w "folderze libs" w Twoim projekcie. Następnie w gradle dodaj tę linię w swojej kompilacji.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')
}
 1
Author: Pre_hacker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-07 09:25:08

Błąd: (30, 0) nie znaleziono metody Gradle DSL: 'classpath ()' Możliwe przyczyny:

  • Projekt ' cid 'może używać wersji wtyczki Android Gradle, która nie zawiera tej metody(np.' testCompile ' został dodany w 1.1.0). Upgrade plugin do wersji 2.3.3 i sync project
  • Projekt ' cid ' może używać wersji Gradle, która nie zawiera tej metody. Open Gradle wrapper file
  • w pliku kompilacji może brakować wtyczki Gradle. Apply Gradle plugin
  •  0
    Author: Eshan Chattaraj,
    Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
    2017-08-30 06:11:40

    Dla android API 28 i wyższych w oczywisty sposób.xml wewnątrz znacznika aplikacji

        <application
        .
        .
        .
    
        <uses-library android:name="org.apache.http.legacy" android:required="false"/>
    
     0
    Author: Wowo Ot,
    Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
    2020-03-17 19:23:50

    Myślę, że w zależności od wersji Android Studio masz, ważne jest, aby zaktualizować android studio, jak również, byłem coraz sfrustrowany zbyt po porady wszystkich, ale bez powodzenia, aż musiałem uaktualnić moją wersję Androida z 1.3 do 1.5, błędy zniknęły jak magia.

     -1
    Author: steven89806,
    Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
    2016-03-14 08:57:20