无法解析符号 HttpEntity、HttpResponse

Cannot Resolve Symbol HttpEntity,HttpResponse

我正在尝试使用 this 教程学习 XML 解析,但是某些 类 没有被导入。这是代码:

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;
}

这些 类 没有被导入:

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

我的 Gradle 属性:

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'
}

HTTP client 在 sdk 23 上已弃用,请改用 HttpURLConnection

或将此添加到您的 gradle(不推荐)

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

编辑

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

软件包 org.apache.http 已在 API 23 中删除。 如果你想用它来学习,使用较低的API,或者寻找替代品。看到这个link:

您可以在 build.gradle(模块:app)中添加: sdk 23 不支持 HttpClient。您必须使用 URLConnection 或降级到 sdk 22。

如果您需要 sdk 23,请将其添加到您的 gradle:

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