Android URLConnection POST instead of GET - android

I have an app that needs to POST several values to a URL, and return the XML response so that it can be parsed. Currently, the request is sending the values via the URL. Below is my current working code, but I'm not able to find any information on the android developers site about POST with URLConnection. Is it possible? Any examples? thank you in advance for any help!
String url = "http://www.mywebsite.com/xml/page.cfm";
StringBuilder sb = new StringBuilder(url);
sb.append("?id=" + id);
URLConnection conn = new URL(sb.toString()).openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
XMLDataHandler h = new XMLDataHandler();
xr.setContentHandler(h);
xr.parse(new InputSource(conn.getInputStream()));
XMLData = XMLDataHandler.XMLData;

Looks like you should use HttpURLConnection.
This post may help you:
How to add parameters to HttpURLConnection using POST

Related

OKHTTP response XMLPullParser

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?
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.

MalformedURLException: Protocol not found. RSS feeds on Android

I'm using the code to parse RSS from this link IBM - Working with XML on Android...and I have little problem with the URL's. If I use this URL:
static String feedUrl = "http://clarin.feedsportal.com/c/33088/f/577681/index.rss";
It works right, but if I use this URL:
static String feedUrl = "http://www.myworkingdomain.com/api/?m=getFeed&secID=163&lat=0&lng=0&rd=0&d=1";
It gives me:
07-07 19:41:30.134: E/AndroidNews(5454): java.lang.RuntimeException: java.net.MalformedURLException: Protocol not found:
I've already tried hints from other answers...but none of them help me out...
Any other solution?
Thanks for your help!
Seeing your feedUrl, I assume that you want to do an HTTP GET request with parameters. I had a lot of trouble with that too, until I started using a StringBuilder and an HttpClient.
Here's some code, without exception catching:
SAXParserFactory mySAXParserFactory = SAXParserFactory
.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
HttpClient httpClient = new DefaultHttpClient();
StringBuilder uriBuilder = new StringBuilder(
"http://myworkingdomain.com/api/");
uriBuilder.append("?m=getFeed");
uriBuilder.append("&secID=163");
[...]
HttpGet request = new HttpGet(uriBuilder.toString());
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
if (status != HttpStatus.SC_OK) {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
response.getEntity().writeTo(ostream);
Log.e("HTTP CLIENT", ostream.toString());
}
InputStream content = response.getEntity().getContent();
// Process feed
InputSource myInputSource = new InputSource(content);
myInputSource.setEncoding("UTF-8");
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
content.close();
Hope this helps!

Android XML SAXParser handling ampersand from URL?

I am parsing XML from URL using SAXParser. The XML has some data with ampersand (&) sign. XML data is not read after the ampersand. How would I resolve this issue?
URL website = new URL(FullURL);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingwork = new HandlingXMLStuff();
xr.setContentHandler(doingwork);
xr.parse(new InputSource(website.openStream()));
String information = doingwork.getInformation();
XML tag has data like
<choice>Cat & Dog</choice>
I am getting output as
Cat
To have a naked '&' rather than "&" you need to use a CDATA[[]] structure around the "Cat & Dog".

Android, SAX and Cookies: How to add a cookie when trying to parse XML from an URL

I want to parse the result of a specific URL using Simple Ajax for XML. This is basically my Code:
URL link = new URL(url); // url is just a string representing the url
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(myHandler); // the class of myHandler extends from DefaultHandler
InputStream stream = link.openStream();
InputSource inputSource = new InputSource(stream);
inputSource.setEncoding("ISO-8859-1");
xr.parse(inputSource);
But how can I add a cookie? I know I can add Cookies to HttpClients like so:
BasicClientCookie cookie = new BasicClientCookie("access_token", accessToken);
mHttpClient.getCookieStore().addCookie(cookie);
HttpGet request = new HttpGet("www.reeple.net/xml/login/" + uid);
mHttpClient.execute(request);
But how can I add a cookie to a request, that is handlet by the SAX-Api?
Step #1: Use HttpClient to retrieve the XML as a string, using whatever cookies you want
Step #2: Use SAX to parse the string retrieved by HttpClient

Convert a String or a InputStreamReader into InputSource

I just read some tutorials in order to parse a xml feed from the web and turn them into a Listview:
URL file = new URL("http://..../file.xml");
SAXParserFactory fabrique = SAXParserFactory.newInstance();
SAXParser parseur = fabrique.newSAXParser();
XMLReader xr = parseur.getXMLReader();
ReglageParseur gestionnaire = new ReglageParseur();
xr.setContentHandler(gestionnaire);
xr.parse(new InputSource(file.openStream()));
Everything is fine and I am able to parse xml.
My second step is to store the xml file from web into a xml file on the phone and only update it when user ask it. ( In fact, this xml file should not change or maybe once every 6 month, so I don't want to download it each time.)
So, what I did is to store the file on the phone and update it on user demand.
And I can read it by doing:
fIn = openFileInput("fichier.xml");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[255];
isr.read(inputBuffer);
String readString = new String(inputBuffer);
So, for now, everything seem fine and I am nearly happy.
The problem is now when I want to parse the new file on the phone:
xr.parse(InputSource);
I need an InputSource as parameter.
So my question is:
How can I turn my file in the phone into a InputSource?
I succeed to have a InputStreamReader or a String but would like to convert that into InputSource.
Thank a lot for any precious help
Well, I don't know what constructors are available on the Android version, but the J2SE InputSource class has a constructor with a Reader parameter. Have you tried that?
Alternatively, why not just construct an InputSource directly from the InputStream? I assume fIn is a FileInputStream? Why not just call:
InputSource input = new InputSource(fIn);
?
the best suitable line for me to convert string to InputSource is :
String myStringObject = "Hello this is string object to convert in InputSource";
InputSource inSource = new InputSource(new StringReader(myStringObject));

Categories

Resources