by desuvinodkumar » Thu Oct 15, 2009 5:59 am
Here the Helper class for HTTPClient /URL Conn /SAX/ DOm PArser....
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class HttpClientHelper {
/**
* Performs a get request with the Apache HttpClient component.
*
* @param url Url to perform the request on.
* @return The Http response or null, if an error occurred.
*/
public String performGetRequest (String url) {
String result = null;
// Create an instance of HttpClient.
HttpClient httpclient = new DefaultHttpClient();
// Create a method instance.
HttpGet httpget = new HttpGet(url);
Log.v("Demo", "Executing request " + httpget.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
// Execute the request and recieve the response.
result = httpclient.execute(httpget, responseHandler);
// If you need some more informations about the connection e.g.
// the status code, you can work with HttpResponse and do stuff
// like that:
// HttpResponse response = httpclient.execute(httpget);
// int statuscode = response.getStatusLine().getStatusCode();
// Log.v("Demo", "Request executed. Result: " + statuscode);
//
// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// StringBuilder stringBuilder = new StringBuilder();
// String line = null;
//
// while ((line = bufferedReader.readLine()) != null) {
// stringBuilder.append(line + "\n");
// }
//
// bufferedReader.close();
// result = stringBuilder.toString();
} catch (ClientProtocolException e) {
Log.v("Demo", "ClientProtocolException " + e.toString());
result = null;
} catch (IOException e) {
Log.v("Demo", "IOException " + e.toString());
result = null;
}
// Shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
return result;
}
}
URL Connection Siippet class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
public class UrlConnectionHelper {
/**
* Performs a get request with the HttpURLConnection class.
*
* @param u Url to perform the request on.
* @return The Http response or null, if an error occurred.
*/
public String performGetRequest (String u) {
String result = null;
URL url;
try {
url = new URL(u);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.v("Demo", "Request executed. Result: " + conn.getResponseCode());
result = null;
}
else {
InputStream in = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
bufferedReader.close();
result = stringBuilder.toString();
}
} catch (MalformedURLException e) {
Log.v("Demo", "MalformedURLException " + e.toString());
result = null;
} catch (IOException e) {
Log.v("Demo", "IOException " + e.toString());
result = null;
}
return result;
}
}
Here the SAX PArsing Code .......
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
import de.michaelhuebl.demo.Location;
public class parseXmlWithSax extends DefaultHandler {
ArrayList<Location> locations = new ArrayList<Location>();
Boolean tagTitle = false;
Boolean tagBusinessClickUrl = false;
Location l;
/**
* Gets called, whenever a new tag is found.
*/
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
// If <Result>-tag was found, a new location must be created.
if (localName.equals("Result")) {
l = new Location();
}
// A <title>-tag was found. Start recording text in characters().
if (localName.equals("Title")) {
tagTitle = true;
}
// A <BusinessClickUrl>-tag was found. Start recording text in characters().
if (localName.equals("BusinessClickUrl")) {
tagBusinessClickUrl = true;
}
}
/**
* Gets called, whenever a closed tag is found.
*/
@Override
public void endElement(String uri, String localName, String name) throws SAXException {
// <Result>-tag is closed. Save the location, as there will be
// a new location created when the next <Result> is found.
if (localName.equals("Result")) {
locations.add(l);
}
// A closed <title>-tag was found. Don't record text anymore.
if (localName.equals("Title")) {
tagTitle = false;
}
// A closed <BusinessClickUrl>-tag was found. Don't record text anymore.
if (localName.equals("BusinessClickUrl")) {
tagBusinessClickUrl = false;
}
}
/**
* Gets called whenever text is found. For example between <Title> and </Title>
*/
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
// The text is between the Title-tags. Record it and save it in the object.
if (tagTitle == true) {
String s = new String(ch,start,length).trim();
l.setTitle(s);
}
// The text is between the Title-tags. Record it and save it in the object.
if (tagBusinessClickUrl == true) {
String s = new String(ch,start,length).trim();
l.setBusinessClickUrl(s);
}
}
/**
* Parses a XML with SAX.
* Call getParseResult() to get the result.
*
* @param xml XML-Code that should be parsed.
*/
public void parseXml(String xml) {
try {
// New SAX parser
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser;
saxParser = factory.newSAXParser();
// Parse xml file with give XML
saxParser.parse(new InputSource(new StringReader(xml)), this);
} catch (ParserConfigurationException e) {
Log.v("Demo", "ParserConfigurationException " + e.toString());
} catch (SAXException e) {
Log.v("Demo", "ParserConfigurationException " + e.toString());
} catch (IOException e) {
Log.v("Demo", "ParserConfigurationException " + e.toString());
}
}
/**
* Returns the result of xml parsing.
* Call this after calling parseXML().
*
* @return ArrayList
*/
public ArrayList<Location> getParseResult() {
return locations;
}
}
Here the DOm PArsing Code........
javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
import de.michaelhuebl.demo.Location;
public class ParseXmlWithDom {
ArrayList<Location> locations = new ArrayList<Location>();
/**
* Parses an given XML. Saves it in the titleOfRestaurants
* ArrayList.
* <br>
*
* Required XML-pattern:
* <Result>
* <Title/>
* <BusinessClickUrl/>
* </Result>
*
* @param xml XML-code as String
*/
public void parseXml(String xml) {
String sUrl = "";
String sTitle = "";
// Reset the ArrayList
locations.clear();
try {
// Create required instances
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(new StringReader(xml)));
// Get all <Result> tags.
// If there are more than zero tags, we know, that we have a result.
NodeList nl = doc.getElementsByTagName("Result");
if (nl != null && nl.getLength() > 0) {
// Get the title and url for every <Result>-tag
for (int i = 0; i < nl.getLength(); i++) {
Location l = new Location();
// Get the content of the <Result>-tag
Element result = (Element)nl.item(i);
// Get the content of the <Title>-tag inside the <Result>-tag
Element title = (Element) result.getElementsByTagName("Title").item(0);
sTitle = title.getFirstChild().getNodeValue();
l.setTitle(sTitle);
Log.v("Demo", "Content of parsed element: " + sTitle);
// Get the content of the <BusinessClickUrl>-tag inside the <Result>-tag
Element url = (Element) result.getElementsByTagName("BusinessClickUrl").item(0);
if (url.hasChildNodes()) {
sUrl = url.getFirstChild().getNodeValue();
l.setBusinessClickUrl(sUrl);
Log.v("Demo", "Content of parsed element: " + sUrl);
}
// Save the content in the ArrayList
locations.add(l);
}
}
}
catch (ParserConfigurationException e) {
Log.v("Demo", "ParserConfigurationException " + e.toString());
} catch (SAXException e) {
Log.v("Demo", "SAXException " + e.toString());
} catch (IOException e) {
Log.v("Demo", "IOException " + e.toString());
}
}
/**
* Returns the result of xml parsing.
* Call this after calling parseXML().
*
* @return ArrayList
*/
public ArrayList<Location> getParseResult() {
return locations;
}
}
Vinod...