Friday, February 26, 2010

Http client API Post method implementation:

Android client side
1.create simple activity with edit text.
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);       
        httpHelper = new HttpHelper();
        etContents =(EditText) findViewById(R.id.etContents);
    }


2.Create Name Value Pair add parameters user name and  password. 

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("userName", "nava"));
            nameValuePairs.add(new BasicNameValuePair("password", "nav"));
            HttpResponse response = httpHelper.doPost("URLHERE", nameValuePairs);
           

           
3.Create http post method and set header and entity. Create Default Http Client,Http Context and execute the  http request.

DefaultHttpClient httpClient;
HttpContext localContext;
HttpPost request = new HttpPost(url);
        HttpResponse response = null;   
        Log.d("Service Call ",url);
        try {
            // Set parameters
            if (parameters != null) {
                request.setHeader("Content-Type", "application/x-www-form-urlencoded");
                request.setEntity(new UrlEncodedFormEntity(parameters));
            }           
            response = httpClient.execute(request, localContext);
           
           
        } catch (ClientProtocolException e) {
            // put your code here
        } catch (IOException e) {
            // put your code here
        }

4.Get the response from the server and display the content to edit text

try {               
                InputStream instream = response.getEntity().getContent();
                content = httpHelper.inconvertibility(instream);
                etContents.setText(content);
            } catch (IllegalStateException e1) {               
                e1.printStackTrace();
            } catch (IOException e1) {               
                e1.printStackTrace();
            }


Server side implementation:

1.create simple web application and that application receive the request parameter.

 public void crmLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userName = "";
        String password = "";

        String result = "";

      
        if (request.getParameter("userName") != null) {
            userName = request.getParameter("userName");
        }

        if (request.getParameter("password") != null) {
            password = request.getParameter("password");
        }

2.get the user name and password from the request and set the user name and password to response.

result="userNamee="+userName+""+"password="+password;

        response.setContentType("text/plain");
        response.setHeader("Cache-Control", "no-cache");
        try {
            response.getWriter().write(result);
        } catch (Exception e) {
        }


Sample SAXParser in Android

In this aritcle discuss about  “How to properly parse XML  using a SAXParser”. 

1.Create  a Customized Handler based on the XML
2.Create a ParserHelper Class
3.Implement the parser and get the Data.

Create  a Customized Handler based on the XML
You can create customized handler using the DefaultHandler class for your xml.

Step : 1 [Create a Handler which extends DefaultHandler]
    class MyDefaultHandler extends DefaultHandler {
    }
   



Step : 2 [ Override the Methods and implement the Code]       
   
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        _tmpValue = new String(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (localName.equalsIgnoreCase("uname")) {
            _tmpKey = _tmpValue;
        } else if (localName.equalsIgnoreCase("pwd")) {
            userList.put(_tmpKey.trim(), _tmpValue);
        }
    }


Create a ParserHelper Class
Create an instance for customized handler class
    MyDefaultHandler df = new MyDefaultHandler();   

Create an instance for SAXParserFactory,SAXParser and XMLReader
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();


Set the content Handler
    xr.setContentHandler(df);

Set the XML Content   
Type 1:
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(parseContent));


Type 2:
    URL url = new     URL("http://www.DOMAON.com/File.xmll");
   
   
Parser the XML
    xr.parse(is); [For type1]
    xr.parse(new InputSource(url.openStream())); [For type2]


Implement the parser and get the Data

Create an instance for helper class and call the parserContent method
  
    SAXHelper sh = new SAXHelper();
    sh.parseContent(content);
             

Sample Source

MyDefaultHandler.java


class MyDefaultHandler extends DefaultHandler {

    String _tmpValue = "", _tmpKey = "";
    public HashMap<String, String> userList = new HashMap<String, String>();

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        _tmpValue = new String(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (localName.equalsIgnoreCase("uname")) {
            _tmpKey = _tmpValue;
        } else if (localName.equalsIgnoreCase("pwd")) {
            userList.put(_tmpKey.trim(), _tmpValue);
        }
    }
}


SAXHelper.java
public class SAXHelper {   
    public HashMap<String, String> userList = new HashMap<String, String>();
    public void parseContent(String parseContent) {
        MyDefaultHandler df = new MyDefaultHandler();
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();           
            xr.setContentHandler(df);
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(parseContent));           
            xr.parse(is);           
            userList = df.userList;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Implementation Class

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        String content = "<root><uname>ganesan</uname><pwd>pwd2</pwd> <uname>rama</uname><pwd>pwd1</pwd> </root>";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.TextView01);
        SAXHelper sh = new SAXHelper();
        sh.parseContent(content);
        String data = (String) sh.userList.get("ganesan");
        Log.d("DATA", data);
        tv.setText(data);

    }
}