Search code examples
androidxml-parsingandroidhttpclient

Cannot Resolve Symbol HttpEntity,HttpResponse


I am trying to learn XML parsing using this tutorial but some of the classes are not getting imported. Here is the code:

public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse resp = client.execute(uri);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}

These classes are not getting imported:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.impl.client.DefaultHttpClient;

My Gradle properties:

android {
    compileSdkVersion 23
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.example.rr.rio"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

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

Solution

  • HTTP client is deprecated on sdk 23, use HttpURLConnection instead

    or add this to your gradle (not recommended)

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

    EDIT

    public String getXmlFromUrl(String urlString) {
        String xml = null;
    
        URL url;
        HttpURLConnection urlConnection = null;
    
        try {
            url = new URL(urlString);
    
            urlConnection = (HttpURLConnection) url.openConnection();
    
            InputStream in = urlConnection.getInputStream();
    
            InputStreamReader isw = new InputStreamReader(in);
    
            BufferedReader br = new BufferedReader(isw);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line+"\n");
            }
            br.close();
    
            xml = sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    
        // return XML
        return xml;
    }
    

    http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client