views:

532

answers:

1

I am trying to call a restful webservice (that needs to require authentication) from my android app. I am doing this successfully already with a url that does not require authentication, but am not sure of the correct approach to use if I want to set up a url that does require authentication. I am currently consuming xml using a Sax Parser and calling url.openStream() like this:

`

                    URL url = new URL('MyUnAuthenticatedURL');
  SAXParserFactory spf = SAXParserFactory.newInstance();
  SAXParser sp = spf.newSAXParser();
  XMLReader xr = sp.getXMLReader();


  final QuestionHandler myQuestionHandler = new QuestionHandler();
  xr.setContentHandler(myQuestionHandler);
  xr.parse(new InputSource(url.openStream()));


  handler.post(new Runnable() {
   public void run() {
    recentQuestions = myQuestionHandler.getResultList();
    loadQuestions = false;
    fillData();
   }
  });

`

I read that I should use org.apache.http.impl.client.DefaultHttpClient in order to take advantage of HTTP Basic Authentication using default session cookies, but I don't understand how this should be done in conjunction with the the Sax Parser.

The main goal here is that I want to call a url that requires an authenticated username, and have that url return XML if the username is authenticated with a password.

Can someone point me in the right direction? Thanks!

A: 

I believe I've done what you are asking for in ChandlerQE. See ChandlerQE.java for the run() method. The code is not pretty, but basically I am using httpclient to post and get, and parse the returned XML with SAXParser.

Heikki Toivonen
Thank you for your code example. I am trying to follow your example, but I am confused because you are expecting a HttpResonse, and my webservice is set up to return a javax.ws.rs.core.Response - (using spring and CXF). Which response type do I need to be returning?
I am confused. What does it matter on the Android client side what you use on the server side to send the response? The response is just text over the wire/air.
Heikki Toivonen
Yes you are right. Sorry, I was confused about that for a minute. I thought I had to return a response object that was the same type as the client expected to receive, but apparently it does not matter.
Cool. If my answer worked for you, please mark it as accepted answer. These statistics may determine how likely people are to answer your future questions.
Heikki Toivonen
Yes. You're answer has helped me with the first part of my question. The part I am still confused about is how to make my webservice use the security credentials passed in the httpclient to authenticate the user as well as pass the principal into the webservice method call (Using Spring Security). I have posted a couple of other questions on StackOverflow elaborating on this. If you have expertise on this as well I would appreciate if you could respond to those questions. Thank you!