android android-studio gradle android-gradle apache-httpclient-4.x

HttpClient no importará en Android Studio



android-studio gradle (22)

Tengo una clase simple escrita en Android Studio:

package com.mysite.myapp; import org.apache.http.client.HttpClient; public class Whatever { public void headBangingAgainstTheWallExample () { HttpClient client = new DefaultHttpClient(); } }

y de esto obtengo el siguiente error de tiempo de compilación:

Cannot resolve symbol HttpClient

¿No HttpClient incluye HttpClient en el SDK de Android Studio? Incluso si no es así, lo agregué a mi compilación de Gradle de esta manera:

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

Con o sin la última línea de compilación, el error es el mismo. ¿Qué me estoy perdiendo?


Otra forma es si tiene el archivo httpclient.jar , entonces puede hacer esto:

Pegue su archivo .jar en la "carpeta libs" en su proyecto. Luego, en gradle, agregue esta línea en su build.gradle (Módulo: aplicación)

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


¿Qué objetivo de API tienes dentro de tu proyecto? AndroidHttpClient es solo para API Nivel 8 <. y por favor mira here

disfruta tu código :)


1- descargue los archivos jar de Apache (a partir de esta respuesta) 4.5.zip desde:
https://hc.apache.org/downloads.cgi?Preferred=http%3A%2F%2Fapache.arvixe.com%2F

2- abre el zip copia los archivos jar en tu carpeta libs. Puede encontrarlo si va a la parte superior de su proyecto donde dice "Android", encontrará una lista cuando haga clic en él. Asi que,

Android -> Proyecto -> aplicación -> libs

Luego pon frascos allí.

3- En build.gradle (Módulo: aplicación) agregar

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

en

dependency { }

4- En la clase java agregue estas importaciones:

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;


Agregue estas dos líneas bajo dependencias

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

entonces

useLibrary ''org.apache.http.legacy''

bajo el androide


Como se mencionó anteriormente, org.apache.http.client.HttpClient ya no es compatible con:

SDK (nivel API) # 23.

Tienes que usar java.net.HttpURLConnection .

Si desea facilitar su código (y vida) al usar HttpURLConnection , aquí hay un Wrapper de esta clase que le permitirá realizar operaciones simples con GET , POST y PUT usando JSON , como por ejemplo, hacer un 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()

Sientase libre de usarlo.

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


Creo que dependiendo de la versión de Android Studio que tenga, es importante que actualice también su estudio de Android, también me frustraba seguir los consejos de todos, pero no tuve suerte, hasta que tuve que actualizar mi versión de Android de 1.3 a 1.5, los errores desaparecieron como mágico.


El cliente ApacheHttp se elimina en v23 sdk. Puede usar HttpURLConnection o un cliente Http de terceros como OkHttp.

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


Error: (30, 0) Método DSL Gradle no encontrado: ''classpath ()'' Causas posibles:

  • El proyecto ''cid'' puede estar usando una versión del complemento Android Gradle que no contiene el método (por ejemplo, ''testCompile'' se agregó en 1.1.0). Complemento de actualización a la versión 2.3.3 y proyecto de sincronización
  • El proyecto ''cid'' puede estar usando una versión de Gradle que no contiene el método. Abra el archivo contenedor de Gradle
  • Al archivo de compilación le puede faltar un complemento de Gradle. Aplicar el complemento Gradle

  • HttpClient no es compatible con SDK 23 y 23+.

    Si necesita usar el SDK 23, agregue el código siguiente a su gradle:

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

    Me está funcionando. Espero sea útil para ti.


    HttpClient quedó en desuso en el nivel 22 de API y se eliminó en el nivel 23. Todavía puede usarlo en el nivel 23 de API en adelante si es necesario, sin embargo, es mejor pasar a los métodos compatibles para manejar HTTP. Entonces, si está compilando con 23, agregue esto en su build.gradle:

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


    HttpClient ya no es compatible con sdk 23. La versión Android 6.0 (API Nivel 23) elimina la compatibilidad con el cliente Apache HTTP. Tienes que usar

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

    y también agregue el fragmento de código a continuación en su dependencia:

    // solución final http para servicio web (incluida la carga de archivos)

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

    También lo ayudará mientras usa Usar MultipartEntity para cargar archivos .


    Intente esto funcionó para mí Agregue esta dependencia a su archivo build.gradle

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


    La respuesta de TejaDroid en el siguiente enlace me ayudó. No se puede importar org.apache.http.HttpResponse en 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'' ... }


    La versión Android 6.0 (API Nivel 23) elimina la compatibilidad con el cliente Apache HTTP. Por lo tanto, no puede usar esta biblioteca directamente en la API 23. Pero hay una manera de usarla. Agregue useLibrary ''org.apache.http.legacy'' en su archivo build.gradle como se muestra a continuación:

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

    Si esto no funciona, puede aplicar el siguiente truco:

    - Copie org.apache.http.legacy.jar que se encuentra en / plataformas / android-23 / ruta opcional de su directorio Android SDK a la carpeta app / libs de su proyecto.

    - Ahora agregue archivos de compilación (''libs / org.apache.http.legacy.jar'') dentro de la sección de dependencias {} del archivo build.gradle.


    Para usar Apache HTTP para SDK Nivel 23:

    Nivel superior 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/ } ... }

    Notificación del estudio de Android sobre la actualización de Gradle:

    Módulo específico build.gradle - /app/build.gradle

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


    Si necesita SDK 23, agregue esto a su gradle:

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


    Si quieres importar alguna clase como:

    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;

    Puede agregar la siguiente línea en build.gradle (dependencias de 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'' }


    Simplemente puede agregar esto a las dependencias de Gradle:

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


    Simplemente use esto: -

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


    Tienes que agregar solo una línea

    useLibrary ''org.apache.http.legacy''

    en build.gradle (Módulo: aplicación), por ejemplo

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


    en API 22 quedan obsoletos y en API 23 los eliminaron por completo, una solución simple si no necesita todas las cosas elegantes de las nuevas incorporaciones es simplemente usar los archivos .jar de apache que se integraron antes de API 22, pero como archivos .jar separados:

    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


    HttpClient ya no es compatible con sdk 23. URLConnection usar URLConnection o URLConnection a sdk 22 ( compile ''com.android.support:appcompat-v7:22.2.0'' )

    Si necesita SDK 23, agregue esto a su gradle:

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

    También puede intentar descargar e incluir el jar HttpClient directamente en su proyecto o usar OkHttp en OkHttp lugar