Sunday 18 December 2016

Fail to Import org.apache.http.XXX stuff in Android Studio

I was just trying to import these:

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

but they went grey and says "unused ...". This is because 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')

Solution:
If you need sdk 23, add this to Gradle Scripts/build.gradle(Module:app)
          useLibrary 'org.apache.http.legacy'

It looks like the following:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
    applicationId "com.example.xxxx.xxxxxxxxxxample"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  }

.....................

}

Then there will be a pop up saying something changed in Gradle, do you want to Sync? And press Sync, it will re-compile everything and the errors are gone.


ref:
http://stackoverflow.com/questions/32153318/httpclient-wont-import-in-android-studio

No comments:

Post a Comment