1

I am transitioning to OKHttp and i am using SAXParser in my project. How can i parse the OKHttp response to SAXParser? or how else can I parse XML using the library. initially this was how I was doing it:

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

But with OKHTTP, how can i pass Response response = client.newCall(request).execute() to the XML parser?

Sufian
  • 6,405
  • 16
  • 66
  • 120
chrissie w
  • 35
  • 1
  • 2
  • 5

1 Answers1

2

You might try this :

// 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 : in your question you mention XMLPullParser, in your code you're actually using a SAXParser. However, if you have the xml string on your hands, you should do fine with both ways.

Angle.Bracket
  • 1,438
  • 13
  • 29
  • 2
    Nice. You can also call response.body().charStream() to get a reader to pass to your parser. That'll use less memory if your XML document is large (ie. bigger than 1 MiB). – Jesse Wilson Jun 28 '14 at 14:07
  • I'm getting ```Unexpected <! (position:START_DOCUMENT``` I believe this is because of ``` ```, does anybody have a workaround? – frankelot Jul 02 '17 at 15:38