我正在过渡到OKHttp,我在我的项目中使用SAXParser。我如何解析对SAXParser的OKHttp响应?或者如何使用库解析XML。最初我是这样做的:
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
SAXParserFactory factory1 = SAXParserFactory.newInstance();
SAXParser parser = factory1.newSAXParser();
FormHandler handler = new FormHandler();
parser.parse(inputStream, handler);
但是使用OKHTTP,我如何将Response response = client.newCall(request).execute()
传递给XML解析器?
你可以试试:
// 1. get a http response
Response response = client.newCall(request).execute();
// 2. construct a string from the response
String xmlstring = response.body().string();
// 3. construct an InputSource from the string
InputSource inputSource = new InputSource(new StringReader(xmlstring));
// 4. start parsing with SAXParser and handler object
// ( both must have been created before )
parser.parse(inputSource,handler);
PS:在你的问题中,你提到XMLPullParser,在你的代码中,你实际上使用的是SAXParser。但是,如果您手头有xml字符串,那么两种方法都可以。