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 comstackción:
Cannot resolve symbol HttpClient
¿No HttpClient
incluye HttpClient
en el SDK de Android Studio? Incluso si no lo es, lo agregué a mi comstackció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 comstackción, el error es el mismo. ¿Qué me estoy perdiendo?
HttpClient
ya no se admite en sdk 23. URLConnection
usar URLConnection
o degradar 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 contenedor HttpClient directamente en su proyecto o usar OkHttp en su lugar
HttpClient quedó obsoleto en el Nivel 22 de la API y se eliminó en el Nivel 23 de la API. Todavía puede usarlo en el Nivel 23 de la API y en adelante si es necesario, sin embargo, es mejor pasar a los métodos admitidos para manejar HTTP. Entonces, si está comstackndo con 23, agregue esto en su build.gradle:
android { useLibrary 'org.apache.http.legacy' }
La respuesta de TejaDroid en el enlace de abajo 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' ... }
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 desde el 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' ... }
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'
1- Descarga 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 la copia zip de los archivos jar en tu carpeta libs. Puede encontrarlo si va al principio de su proyecto, donde dice “Android”, encontrará una lista cuando haga clic en él. Asi que,
Android -> Proyecto -> aplicación -> libs
, Luego pon jarros allí.
3- En build.gradle (Módulo: aplicación) agregar
compile fileTree(dir: 'libs', include: ['*.jar'])
en
dependency { }
4- En la clase java agrega 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;
HttpClient ya no se admite en sdk 23. La versión de 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 siguiente fragmento de código en su dependencia:
// solución final http para el 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 utiliza Use MultipartEntity para la carga de archivos .
en API 22 quedan obsoletos y en API 23 los eliminaron por completo, una solución simple si no necesitas 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 separados .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
Simplemente puede agregar esto a las dependencias de Gradle:
compile "org.apache.httpcomponents:httpcore:4.3.2"
La versión de Android 6.0 (API nivel 23) elimina la compatibilidad con el cliente Apache HTTP. Por lo tanto, no puede usar esta biblioteca directamente en API 23. Pero hay una forma de usarlo. Agregue useLibrary ‘org.apache.http.legacy’ en su archivo build.gradle de la siguiente manera:
android { useLibrary 'org.apache.http.legacy' }
Si esto no funciona, puede aplicar el siguiente hack-
– Copie org.apache.http.legacy.jar que se encuentra en / platforms / android-23 / ruta opcional de su directorio Android SDK a la carpeta de aplicaciones / libs de su proyecto.
– Ahora agrega archivos de comstackción (‘libs / org.apache.http.legacy.jar’) dentro de la sección de dependencias {} del archivo build.gradle.
ApacheHttp Client se elimina en v23 sdk. Puede usar HttpURLConnection o Http Client de terceros como OkHttp.
ref: https://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client
HttpClient no es compatible con sdk 23 y 23+.
Si necesita usar en sdk 23, agregue el siguiente código a su gradle:
android { useLibrary 'org.apache.http.legacy' }
Funciona para mí. Espero que sea útil para ti
Si necesita sdk 23, agregue esto a su gradle:
android { useLibrary 'org.apache.http.legacy' }
Simplemente usa 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' }
¿Qué objective de API tienes dentro de tu proyecto? AndroidHttpClient
es solo para API Nivel 8 <. y por favor echen un vistazo aquí
disfruta tu código 🙂
Agregue estas dos líneas en dependencias
compile 'org.apache.httpcomponents:httpcore:4.4.1' compile 'org.apache.httpcomponents:httpclient:4.5'
entonces
useLibrary 'org.apache.http.legacy'
bajo el android
Otra forma es si tiene un archivo httpclient.jar entonces puede hacer esto:
Pegue su archivo .jar en la “carpeta libs” en su proyecto. Luego en gradle agrega esta línea en tu 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') }
Como se mencionó anteriormente, org.apache.http.client.HttpClient
ya no se admite en:
SDK (nivel de API) # 23.
Tienes que usar java.net.HttpURLConnection
.
Si desea hacer que su código (y su vida) sea más fácil al usar HttpURLConnection
, aquí hay un Wrapper
de esta clase que le permitirá realizar operaciones simples con GET
, POST
y PUT
utilizando JSON
, como por ejemplo, haciendo 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. * * Copyright © 2017, Calculistik . All rights reserved. *
* Oracle and Java are registered trademarks of Oracle and/or its * affiliates. Other names may be trademarks of their respective owners. *
* 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]" *
* 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 params = new HashMap(); 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 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; } }
Error: (30, 0) No se encontró el método Gradle DSL: ‘classpath ()’ Posibles causas:
Creo que dependiendo de la versión de Android Studio que tengas, también es importante que actualices tu estudio de Android, también me sentía frustrado siguiendo 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 magia.