我正在制作一个安卓应用程序。它有一个 XML 解析器。XML 是我的 api 响应的类型这是我将它下载到 InputStream 的方式:
private InputStream downloadUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String encoded;
encoded = "Basic " + Base64.encodeToString("user:pass".getBytes(), 0);
conn.setRequestProperty("Authorization", encoded);
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
return stream;
}
如果用户和密码正确,则 XML 的输出是:
<status>true</status>
如果不是:
<status>false</status>
解析器类是:
private static final String ns = null;
public Boolean parse(InputStream in) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
return readFeed(parser);
} finally {
in.close();
}
}
private Boolean readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "verify_account");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("status")) {
return readSta(parser);
} else {
skip(parser);
}
}
return false;
}
private Boolean readSta(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "stats");
String name = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "stats");
if (name == "true"){
return true;
}
else {
return false;
}
}
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
问题是 PareXml 类总是返回 false :| 但我打印了标签的值,它是“真”我尝试在 readSta 函数第 4 行的“真”之前和之后添加空格,但它不起作用:| . 这似乎是一个编码问题
我尝试了很多东西,但它仍然无法正常工作:|