HttpEntity is deprecated on Android now, what's the alternative?

前端 未结 3 1524
遇见更好的自我
遇见更好的自我 2020-11-28 07:09

With the release of Android 5.1, it looks like all the Apache http stuff has been deprecated. Looking at the documentation is useless; they all say

This class

3条回答
  •  离开以前
    2020-11-28 08:08

    Call webservice httpclient replace by httpurlconnection

    my code here

    public static String getDataFromUrl(String url) {
            String result = null;
    //        System.out.println("URL comes in jsonparser class is:  " + url);
            try {
                URL myurl=new URL(url);
                HttpURLConnection urlConnection = (HttpURLConnection) myurl
                        .openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setDoInput(true);
                urlConnection.connect();
                InputStream is=urlConnection.getInputStream();
                if (is != null) {
                    StringBuilder sb = new StringBuilder();
                    String line;
                    try {
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(is));
                        while ((line = reader.readLine()) != null) {
                            sb.append(line);
                        }
                        reader.close();
                    } finally {
                      is.close();
                    }
                    result = sb.toString();
                }
            }catch (Exception e){
                result=null;
            }
            return result;
        }
    

提交回复
热议问题