Android API 23 Removed packages

2019-02-14 12:25发布

问题:

What is the best replacement for org.apache.http ?

since they say this in Android API Differences Report .

Removed Packages in API 23

org.apache.commons.logging   
org.apache.http  
org.apache.http.auth     
org.apache.http.auth.params  
org.apache.http.client   
org.apache.http.client.entity    
org.apache.http.client.methods   
org.apache.http.client.params    
org.apache.http.client.protocol  
org.apache.http.client.utils     
org.apache.http.conn.params  
org.apache.http.conn.routing     
org.apache.http.conn.util    
org.apache.http.cookie   
org.apache.http.cookie.params    
org.apache.http.entity   
org.apache.http.impl     
org.apache.http.impl.auth    
org.apache.http.impl.client  
org.apache.http.impl.conn    
org.apache.http.impl.conn.tsccm  
org.apache.http.impl.cookie  
org.apache.http.impl.entity  
org.apache.http.impl.io  
org.apache.http.io   
org.apache.http.message  
org.apache.http.protocol     
org.apache.http.util

回答1:

Like Blackbelt stated, HttpURLConnection is the default replacement for the HTTPClient. If you chek here (at the end), you may see that thats where they will be focusing their resources.

However, is worth mentioning that some common APIs are being used, and works nicely if the focus of your app is not web browsing, but rather just using internet to fetch imgs, jsons, texts, etc.

I recommend Volley. It does look like it will be supported for a long time (based on my opinion), and is supported by google itself.



回答2:

If you are updating your project and you want continue using the Apache HTTP APIs, you must declare the following in your build.gradle file: (More info here)

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

Watch out about your gradle version used, I'm using 2.6 at my gradle-wrapper.properties

distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-all.zip


回答3:

You are right DefaultHttpClient and AndroidHttpClient both network class are deprecated.

Now, only HttpUrlConnection is a class will get used as replacement of them. Some of the usage on Android developer site.

"Happy Coding...!!!"



回答4:

After 3 days of seaching and reading about HttpUrlConnection & CookieManager

I find Alot of Questions about it And more Questions About sending Cookies with it

So I make a complete solution for it :

for Handle Cookies :

static CookieManager myCookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL);

final public static void saveCookies(HttpURLConnection connection , Context context) {
Map<String, List<String>> headerFields = connection.getHeaderFields();

List<String> cookiesHeader = null;
try {
    cookiesHeader = headerFields.get("Set-Cookie");
} catch (Exception e) {
    e.printStackTrace();
}

if (cookiesHeader != null && myCookies != null) {
    for (String cookie : cookiesHeader) {
        try {
            cookie = cookie.replace("\"", "");
            myCookies.getCookieStore().add(connection.getURL().toURI(), HttpCookie.parse(cookie).get(0));
            String new_cookie = TextUtils.join(";", myCookies.getCookieStore().getCookies());

            PreferenceManager.getDefaultSharedPreferences(context).edit().putString("cookie", new_cookie).commit();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
}

final public static void loadCookies(HttpURLConnection connection , Context context) {
if (myCookies != null && myCookies.getCookieStore().getCookies().size() > 0) {
    connection.setRequestProperty("Cookie", TextUtils.join(";", myCookies.getCookieStore().getCookies()));
}
else {
    String new_cookie = PreferenceManager.getDefaultSharedPreferences(context).getString("cookie" , "");
    connection.setRequestProperty("Cookie", new_cookie );
}
}

For Post Request With Json Data

  public String  URL_Connectin_Post ( String  endPoint , JSONObject data , Context context )
{
    URL url;
    try {
        url = new URL(baseUrl + endPoint);

        urlConnection = (HttpURLConnection) url.openConnection();
        loadCookies(urlConnection , context);
        urlConnection.setReadTimeout(15000);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        /* optional request header */
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("charset", "UTF-8");
        urlConnection.addRequestProperty("Accept-Encoding", "UTF-8");

        /* optional request header  with UTF-8*/
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

        /*  use this when you know data length  */
        urlConnection.setFixedLengthStreamingMode(data.toString().getBytes("UTF-8").length);

        /*  use this when you dont  know data length  */
  //      urlConnection.setChunkedStreamingMode(100);

        urlConnection.setUseCaches(true);
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();

        OutputStream os = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
        writer.write(data.toString());
        writer.flush();
        writer.close();
        os.close();

        int responseCode=urlConnection.getResponseCode();
        if (responseCode == HttpsURLConnection.HTTP_OK)
        {
            InputStream in = urlConnection.getInputStream();
            saveCookies(urlConnection , context);
            Result = convertStreamToString(in);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return Result;
}

For Get Request

    public  String URL_Connectin_Get(String  endPoint , Context context)
{
    URL url;
    try {
        url = new URL(baseUrl + endPoint);

        urlConnection = (HttpURLConnection) url.openConnection();
        loadCookies(urlConnection , context);

        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("charset", "UTF-8");
        urlConnection.addRequestProperty("Accept-Encoding", "UTF-8");
        urlConnection.setDoInput(true);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        int responseCode=urlConnection.getResponseCode();
        if (responseCode == HttpsURLConnection.HTTP_OK) {

            InputStream in = urlConnection.getInputStream();
            if (urlConnection.getContentEncoding() != null && urlConnection.getContentEncoding().contains("gzip")) {
                GZIPInputStream inn = new GZIPInputStream(in);
                saveCookies(urlConnection , context);
            } else {
                saveCookies(urlConnection  , context);
            }
            Result = convertStreamToString(in);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    return Result ;
}