我正在尝试使用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'
}
答案 0 :(得分:10)
HTTP client
,而使用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;
}
答案 1 :(得分:2)
您可以在build.gradle(Module:app)中添加: sdk 23不支持HttpClient。您必须使用URLConnection或降级到sdk 22.
OR
如果您需要sdk 23,请将其添加到您的gradle:
android {
useLibrary 'org.apache.http.legacy'
}
答案 2 :(得分:0)
在API 23中删除了包org.apache.http
。
如果您想将其用于学习,请使用较低的API,或查找替代方案。请看这个链接:HttpEntity is deprecated on Android now, what's the alternative?