Android Studio无法找到httpclient代码的替代品(它不再适用于android 25)

时间:2017-02-05 13:49:43

标签: android httpclient

这是不起作用的代码。我在网上找到它,我尝试自己使用它,但HTTP的代码总是通过它而且它不起作用。我认为它是因为它已经过时但我已经在互联网上搜索并且找不到答案所以我想我可能会在这里问它。

private class BackTask extends AsyncTask<Void,Void,Void> {
        ArrayList<String> list;
        protected void onPreExecute(){
            super.onPreExecute();
            list=new ArrayList<>();
        }
        protected Void doInBackground(Void...params){
            InputStream is=null;
            String result="";
            try{
                HttpClient httpclient=new DefaultHttpClient();
                HttpPost httppost= new HttpPost("http://10.0.2.2:8080/getInterviewees.php");
                HttpResponse response=httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                // Get our response as a String.
                is = entity.getContent();
            }catch(IOException e){
                e.printStackTrace();
            }

            //convert response to string
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    result+=line;
                }
                is.close();
                //result=sb.toString();
            }catch(Exception e){
                e.printStackTrace();
            }
            // parse json data
            try{
                JSONArray jArray =new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                    JSONObject jsonObject=jArray.getJSONObject(i);
                    // add interviewee name to arraylist
                    list.add(jsonObject.getString("iname"));
                }
            }
            catch(JSONException e){
                e.printStackTrace();
            }
            return null;
        }
        protected void onPostExecute(Void result){
            listItems.addAll(list);
            adapter.notifyDataSetChanged();
        }
    }

3 个答案:

答案 0 :(得分:0)

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

defaultConfig {
    ...
}

在你的build.gradle上使用它来获取app。

答案 1 :(得分:0)

尝试在gradle文件中添加此内容。

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

答案 2 :(得分:0)

或者你可以简单地使用httpUrlConnection代替那个......