By AndroidDev


2015-08-22 06:56:51 8 Comments

I have a simple class written in Android Studio:

package com.mysite.myapp;

import org.apache.http.client.HttpClient;

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

and from this I get the following compile time error:

Cannot resolve symbol HttpClient

Isn't HttpClient included in the Android Studio SDK? Even if it is not, I added it to my Gradle build like this:

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

With or without the last compile line, the error is the same. What am I missing?

22 comments

@A.Bahrami 2018-09-29 17:12:42

If you want import some class like :

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;

You can add the following line in the build.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'

}

@karenms 2018-10-21 07:11:00

Perfect answer! I had to use the wrapped.org.apache since I needed to update a very old project. Thanks.

@Anish Arya 2019-01-30 15:58:16

The last dependency worked for me, thanks a lot

@fullMoon 2015-09-08 13:58:28

1- download Apache jar files (as of this answer) 4.5.zip file from:
https://hc.apache.org/downloads.cgi?Preferred=http%3A%2F%2Fapache.arvixe.com%2F

2- open the zip copy the jar files into your libs folder. You can find it if you go to the top of your project where it says "Android" you'll find a list when u click it. So,

Android -> Project -> app -> libs

,Then put jars there.

3- In build.gradle (Module: app) add

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

in

 dependency { 
   }

4- In the java class add these imports:

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;

@Eshan Chattaraj 2017-08-30 06:11:40

Error:(30, 0) Gradle DSL method not found: 'classpath()' Possible causes:

  • The project 'cid' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0). Upgrade plugin to version 2.3.3 and sync project
  • The project 'cid' may be using a version of Gradle that does not contain the method. Open Gradle wrapper file
  • The build file may be missing a Gradle plugin. Apply Gradle plugin
  • @Ilya Blokh 2015-08-22 07:12:56

    HttpClient is not supported any more in sdk 23. You have to use URLConnection or downgrade to sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')

    If you need sdk 23, add this to your gradle:

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

    You also may try to download and include HttpClient jar directly into your project or use OkHttp instead

    @dhke 2015-08-22 07:15:52

    @android developer 2015-09-03 12:04:51

    It doesn't do anything in my case. How come?

    @fullMoon 2015-09-08 11:05:46

    useLibrary cannot be resolved when I add it. My target is 23, what i'm I missing?

    @fullMoon 2015-09-08 19:41:55

    @androiddeveloper, I was the same. See my answer below.

    @powder366 2015-09-11 15:00:53

    They use this in license vending code. Have they upgraded this for M also?

    @YETI 2015-09-16 07:46:46

    android { useLibrary 'org.apache.http.legacy' } [when u add this] [1] 'org.apache.http' android-studio still have tips:'Cannot resolve symbol' [2] this make android-studio(with sdk23) can build. though there have tips(Cannot resolve symbol) [3] if u add jar,it no tips,can build,but!!!cannot run,because it has two copy 'org.apache.http'

    @Ilya Blokh 2015-09-16 13:25:13

    @YETI did you remove httpclient import from gradle when you try to use jar?

    @Ilya Blokh 2015-09-16 13:27:18

    @androiddeveloper did you succeed with importing jar?

    @android developer 2015-09-16 13:30:44

    @IlyaBlokh No. We will probably use OkHttp or something.

    @YETI 2015-09-17 06:36:27

    @llyaBloch (1) User jars (2) Use/Unuse [useLibrary 'org.apache.http.legacy'] (result1) can build (result2) cannot run:[Error:Execution failed for task ':app:dexDebug'. > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_45\bin\java.exe'' finished with non-zero exit value 2]

    @Nabdreas 2015-11-05 10:26:30

    useLibrary 'org.apache.http.legacy' works like a dream for me, add, sync gradle and i can use httpclient! thanks man, saved me a lot of time from re-writing the code!

    @Kairi San 2015-11-16 02:50:37

    Thank you for this! It is really a big help! :)

    @sravan953 2016-01-18 17:15:44

    For anyone out there using the Volley library, take note that this gradle line addition should go into the gradle file for the library, and not your app. Works perfectly! Thanks a ton!

    @Alejandro Pablo Tkachuk 2017-06-08 17:01:12

    As mentioned before, org.apache.http.client.HttpClient is not supported any more in:

    SDK (API level) #23.

    You have to use java.net.HttpURLConnection.

    If you want to make your code (and life) easier when using HttpURLConnection, here is a Wrapper of this class that will let you do simple operations with GET, POST and PUT using JSON, like for example, doing a 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()
    

    Feel free to use it.

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

    @Nilesh Panchal 2016-12-03 11:17:51

    You have to add just one line

    useLibrary 'org.apache.http.legacy'
    

    into build.gradle(Module: app), for example

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

    @Ramindu Rusara Senarath 2016-11-19 05:35:52

    Add these two lines under dependencies

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

    then

    useLibrary 'org.apache.http.legacy'
    

    under the android

    @ShivBuyya 2016-07-12 06:56:19

    If you need sdk 23, add this to your gradle:

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

    @Sneha Patel 2016-07-11 10:05:36

    HttpClient is not supported in sdk 23 and 23+.

    If you need to use into sdk 23, add below code to your gradle:

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

    Its working for me. Hope useful for you.

    @Daksh Mehta 2017-06-06 20:37:10

    Worked perfectly with SDK version 24

    @steven89806 2016-03-14 08:57:20

    I think depending on which Android Studio version you have, it's important you update your android studio as well, i was becoming frustrated too following everyone's advice but no luck, until i had to upgrade my android version from 1.3 to 1.5, the errors disappeared like magic.

    @Pritish Joshi 2015-12-12 05:08:19

    Try this worked for me Add this dependency to your build.gradle File

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

    @android_sh 2016-02-18 08:03:02

    HttpClient is not supported any more in sdk 23. Android 6.0 (API Level 23) release removes support for the Apache HTTP client. You have to use

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

    and also add below code snippet in your dependency :

    //http final solution for web-service (including file uploading)

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

    It will also help you while you use Use MultipartEntity for File upload.

    @android_sh 2016-05-18 10:39:42

    Glad to hear that it helps you :)

    @DaniG 2016-11-21 20:23:37

    I have problems with that... duplicate entry: org/apache/http/HttpHeaders.class. Do you know what's the problem?

    @AndreyICE 2015-09-17 09:28:07

    To use Apache HTTP for SDK Level 23:

    Top level 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/
        }
        ...
    }
    

    Notification from Android studio about gradle update:

    Notification from Android studio about gradle update

    Module specific build.gradle - /app/build.gradle

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

    @Kaushal Kishor 2015-12-29 12:49:48

    Simply use this :-

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

    @user3766643 2015-12-24 02:40:53

    Android 6.0 (API Level 23) release removes support for the Apache HTTP client. Hence you can not use this library directly in API 23. But there is a way to use it. Add useLibrary ‘org.apache.http.legacy’ in your build.gradle file as below-

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

    If this does not work you may apply the following hack-

    – Copy org.apache.http.legacy.jar which is in /platforms/android-23/optional path of your Android SDK directory to your project’s app/libs folder.

    – Now Add compile files(‘libs/org.apache.http.legacy.jar’) inside dependencies{} section of build.gradle file.

    @Joseph 2017-08-22 11:35:48

    The last option you gave does the job well. I appreciate.

    @Pre_hacker 2015-12-07 09:25:08

    Another way is if you have httpclient.jar file then you can do this :

    Paste your .jar file in "libs folder" in your project. Then in gradle add this line in your 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')
    }
    

    @Vinay 2015-10-29 04:28:26

    TejaDroid's answer in below link helped me . Can't import org.apache.http.HttpResponse in 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'
        ...
    }
    

    @pt123 2016-01-16 01:48:00

    thanks this is the only solution that worked with the new eperimental builds as useLibrary is not recognised in it

    @Matan Dahan 2016-05-30 12:01:03

    This is actually a better answer than the one above! it works with newer versions of the compiler

    @Mostafa Abdellateef 2015-09-28 12:38:40

    You can simply add this to Gradle dependencies:

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

    @AlexAndro 2015-10-05 09:10:22

    This helps. But still not enough if you want to use other classes like HttpGet. For that I used compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped‌​.org.apache.http.cli‌​ent:4.1.2'

    @Catalin 2015-09-17 17:27:33

    in API 22 they become deprecated and in API 23 they removed them completely, a simple workaround if you don't need all the fancy stuff from the new additions is to simply use the .jar files from apache that were integrated before API 22, but as separated .jar files:

    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
    

    @straya 2015-08-22 14:52:22

    HttpClient was deprecated in API Level 22 and removed in API Level 23. You can still use it in API Level 23 and onwards if you must, however it is best to move to supported methods to handle HTTP. So, if you're compiling with 23, add this in your build.gradle:

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

    @YETI 2015-09-16 07:44:31

    android { useLibrary 'org.apache.http.legacy' } [when u add this] [1] 'org.apache.http' android-studio still have tips:'Cannot resolve symbol' [2] this make android-studio(with sdk23) can build. though there have tips(Cannot resolve symbol) [3] if u add jar,it no tips,can build,but!!!cannot run,because it has two copy 'org.apache.http'

    @straya 2015-09-16 23:27:14

    [2.1] So close Android Studio and start it again, don't open the file(s) that make use of the legacy code and the "tips" won't be applied. If you need to open the file then it suggests you own the code, so [4] you should stop using HttpClient in code you control.

    @YETI 2015-09-17 03:20:36

    Donot know why (build-tool&sdk)23's behavious so freak. Event donot support developer use 'apche http' on one's mind.

    @rawcoder064 2015-10-26 09:58:01

    You have to update the android studio to the latest version to avoid this behavior......its fixed in the new version

    @Janaki 2018-01-12 15:07:24

    Great. It works for me. Thanks

    @waldgeist 2019-07-02 20:34:31

    What are the "supported methods to handle HTTP"?

    @straya 2019-07-03 04:50:09

    @waldgeist behold the power of search: stackoverflow.com/questions/29058727/…

    @waldgeist 2019-07-04 05:41:57

    Thanks. I’ve seen this, but these APIs seem to be way more low level than the Apache APIs.

    @straya 2019-07-04 07:56:35

    @waldgeist I don't know what your particular needs are, have a look at Retrofit

    @waldgeist 2019-07-08 18:13:05

    @straya: Thanks, will do!

    @Kirtan 2015-08-22 07:15:28

    ApacheHttp Client is removed in v23 sdk. You can use HttpURLConnection or third party Http Client like OkHttp.

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

    @Ben Pearson 2015-10-01 10:15:37

    Use of HttpUrlConnection is actually encouraged in lieu of HttpClient

    @John smith 2015-08-22 07:14:49

    Which API target do you have within your project?AndroidHttpClientis only for API Level 8 <. and please have a look on here

    enjoy your code:)

    Related Questions

    Sponsored Content

    97 Answered Questions

    31 Answered Questions

    11 Answered Questions

    [SOLVED] Proper use cases for Android UserManager.isUserAGoat()?

    48 Answered Questions

    [SOLVED] Is there a unique Android device ID?

    20 Answered Questions

    [SOLVED] What is Gradle in Android Studio?

    34 Answered Questions

    [SOLVED] Android Studio: Add jar as library?

    23 Answered Questions

    [SOLVED] Java finished with non-zero exit value 2 - Android Gradle

    Sponsored Content