URLConnection VS HTTPClient & SAX VS DOM Performance ..

Tutorials with advanced 'difficulty' and more Lines of Code.

URLConnection VS HTTPClient & SAX VS DOM Performance ..

Postby desuvinodkumar » Wed Oct 14, 2009 6:37 am

Comparison of HTTP and XML classes in Android

an example of implementing HTTP and XML classes in Android
It's a kind of best practice for the communication with web services.



HTTP classes which are implemented:

* org.apache.http.client.HttpClient
* java.net.HttpURLConnection

XML parser which are implemented:

* javax.xml.parsers.SAXParser (SAX)
* javax.xml.parsers.DocumentBuilder (DOM)

This examples hows you the performance of both HTTP class And XML Parser Speed ....
Vinod...
User avatar
desuvinodkumar
Senior Developer
Senior Developer
 
Posts: 102
Joined: Mon Mar 23, 2009 6:51 am
Location: India

Top

Postby irfan123 » Thu Oct 15, 2009 5:05 am

It wud b greatful if u cud post some sample code for both approaches
Need help to build android application
irfan123
Junior Developer
Junior Developer
 
Posts: 11
Joined: Sun Oct 11, 2009 2:18 am
Location: San Diego

Postby desuvinodkumar » Thu Oct 15, 2009 5:52 am

Here is the MAin Activity Class


public class HttpXmlDemo extends Activity {
private String url1;
private String url2;
private String xmlOutput = "";
private long counter_start = 0;
private long counter_end = 0;
private ArrayList<Location> locations = new ArrayList<Location>();

private Button btn_urlconnection;
private Button btn_httpclient;
private Button btn_dom;
private Button btn_sax;
private TextView txt_xmloutput;
private TextView txt_exectime;
private TextView txt_xmlexectime;
private TextView txt_parsedtext;
private ProgressDialog pd;

private final static int CONNECTED_WITH_API = 1;
private final static int CONNECTED_WITH_URLCONNECTION = 2;
private final static int PARSED_WITH_SAX = 3;
private final static int PARSED_WITH_DOM = 4;

private Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Instantiate View elements
btn_httpclient = (Button) findViewById(R.id.main_btn_httpclient);
btn_httpclient.setOnClickListener(httpClientListener);

btn_urlconnection = (Button) findViewById(R.id.main_btn_urlconnection);
btn_urlconnection.setOnClickListener(urlConnectionListener);

btn_sax = (Button) findViewById(R.id.main_btn_sax);
btn_sax.setOnClickListener(saxListener);

btn_dom = (Button) findViewById(R.id.main_btn_dom);
btn_dom.setOnClickListener(w3cListener);

txt_xmloutput = (TextView) findViewById(R.id.main_txt_xmloutput);
txt_exectime = (TextView) findViewById(R.id.main_txt_exectime);
txt_xmlexectime = (TextView) findViewById(R.id.main_txt_xmlexectime);
txt_parsedtext = (TextView) findViewById(R.id.main_txt_parsedtext);


//Init variables
url1 = "http://local.yahooapis.com/LocalSearchService/V3/localSearch?appid=YahooDemo&query=pizza&zip=94306&results=4";
url2 = "http://local.yahooapis.com/LocalSearchService/V3/localSearch?appid=YahooDemo&query=sushi&zip=94306&results=4";

}



@Override
protected void onStart() {
super.onStart();
//Debug.startMethodTracing("HttpXmlDemo");
// Debug.startMethodTracing("HttpXmlDemo");
}


@Override
protected void onStop() {
super.onStop();
// Debug.stopMethodTracing();
}



/**
* Updates the xml-output view.
*/
private Runnable doUpdateXmlOutput = new Runnable() {
public void run() {
// Connection to API was successful.
// Display the result and stop the ProgressDialog
txt_xmloutput.setText(xmlOutput);
txt_exectime.setText( (counter_end - counter_start) + " ms" );
pd.dismiss();
}
};

/**
* Updates parsed text view.
* Displays the result from parsed XML.
*/
private Runnable doUpdateParsedText = new Runnable() {
public void run() {
String output = "";

for (int i = 0; i < locations.size(); i++) {
String title = locations.get(i).getTitle();
String url = locations.get(i).getBusinessClickUrl();
output += title;
if (url != null && url != "")
output += ": "+url;
output += "n";
}

txt_parsedtext.setText(output);
txt_xmlexectime.setText( (counter_end - counter_start) + " ms" );
pd.dismiss();
}
};

/**
* Calls the HttpClientHelper class to perform
* a get request to Yahoo!-API with HTTPClient.
* Saves the result in xmlOutput.
*/
private Runnable doConnectWithHttpClient = new Runnable() {
public void run() {
String result = null;

counter_start = System.currentTimeMillis();

HttpClientHelper connectionHelper = new HttpClientHelper();
result = connectionHelper.performGetRequest(url1);

counter_end = System.currentTimeMillis();

xmlOutput = result;
//handler.sendEmptyMessage(CONNECTED_WITH_API);
handler.post(doUpdateXmlOutput);
}
};


/**
* Calls the UrlConnectionHelper class to perform
* a get request to Yahoo!-API with URLConnection.
* Saves the result in xmlOutput.
*/
private Runnable doConnectWithUrlConnection = new Runnable() {
public void run() {
String result = null;

counter_start = System.currentTimeMillis();

UrlConnectionHelper connectionHelper = new UrlConnectionHelper();
result = connectionHelper.performGetRequest(url2);

counter_end = System.currentTimeMillis();

xmlOutput = result;

handler.post(doUpdateXmlOutput);
}
};


/**
* Parses the xml from Yahoo!-API with SAX
*/
private Runnable doParsingWithSax = new Runnable() {
public void run() {
counter_start = System.currentTimeMillis();

parseXmlWithSax parser = new parseXmlWithSax();
parser.parseXml(xmlOutput);
locations = parser.getParseResult();

counter_end = System.currentTimeMillis();

handler.post(doUpdateParsedText);
}
};

/**
* Parses the xml from Yahoo!-API with DOM
*/
private Runnable doParsingWithDom = new Runnable() {
public void run() {
counter_start = System.currentTimeMillis();

ParseXmlWithDom parser = new ParseXmlWithDom();
parser.parseXml(xmlOutput);
locations = parser.getParseResult();

counter_end = System.currentTimeMillis();

handler.post(doUpdateParsedText);
}
};


/**
* Listener for the btn_httpclient button.
* Resets the previously displayed output and
* starts a thread which connects the yahoo! API
* with HTTPClient.
*/
private OnClickListener httpClientListener = new OnClickListener() {

@Override
public void onClick(View v) {

// Reset displayed result and start thread
txt_xmloutput.setText("");
txt_parsedtext.setText("");

pd = ProgressDialog.show(HttpXmlDemo.this, "Please wait...", "Connecting local.yahooapis.com", true, false);

Thread t = new Thread(null, doConnectWithHttpClient, "ConnectWithHttpClient");
t.start();
}
};

/**
* Listener for the btn_urlconnection button.
* Resets the previously displayed output and
* starts a thread which connects the yahoo! API
* with URLConnection.
*/
private OnClickListener urlConnectionListener = new OnClickListener() {

@Override
public void onClick(View v) {

// Reset displayed result and start counter
txt_xmloutput.setText("");
txt_parsedtext.setText("");

pd = ProgressDialog.show(HttpXmlDemo.this, "Please wait...", "Connecting local.yahooapis.com", true, false);

Thread t = new Thread(null, doConnectWithUrlConnection, "ConnectWithUrlConnection");
t.start();
}

};


/**
* Listener for the btn_w3c Button.
* Starts parsing the XML.
*/
private OnClickListener saxListener = new OnClickListener() {

@Override
public void onClick(View v) {

pd = ProgressDialog.show(HttpXmlDemo.this, "Please wait...", "Parsing XML with SAX", true, false);

Thread t = new Thread(null, doParsingWithSax, "ParsingWithSax");
t.start();
}
};


/**
* Listener for the btn_dom Button.
* Starts parsing the XML.
*/
private OnClickListener w3cListener = new OnClickListener() {

@Override
public void onClick(View v) {
pd = ProgressDialog.show(HttpXmlDemo.this, "Please wait...", "Parsing XML with DOM", true, false);

Thread t = new Thread(null, doParsingWithDom, "ParsingWithDom");
t.start();

}
};


}





Here the custom class

public class Location {

private String title;
private String businessClickUrl;


public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBusinessClickUrl() {
return businessClickUrl;
}
public void setBusinessClickUrl(String businessClickUrl) {
this.businessClickUrl = businessClickUrl;
}


}
Vinod...
User avatar
desuvinodkumar
Senior Developer
Senior Developer
 
Posts: 102
Joined: Mon Mar 23, 2009 6:51 am
Location: India

Postby 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...
User avatar
desuvinodkumar
Senior Developer
Senior Developer
 
Posts: 102
Joined: Mon Mar 23, 2009 6:51 am
Location: India

Postby irfan123 » Thu Oct 15, 2009 6:21 am

thnx a lot.

i had one more qstn for u. Do u hve any idea to upload videos from android phone to a webserver?
Is it possible to upload large clips?
Need help to build android application
irfan123
Junior Developer
Junior Developer
 
Posts: 11
Joined: Sun Oct 11, 2009 2:18 am
Location: San Diego

Postby Nanis » Thu Oct 15, 2009 9:42 am

Hello, actually I try to find some informations about calling distant servlet. I don't know if I must use HTTPClient or WebService or anything else.

Could you tell me about which one would be the most secure for an application like "web mail" ? Do you know if it existing a class in Android that allows to do this ?
Thank's

ps: sorry for my english i'm french.
Nanis
Freshman
Freshman
 
Posts: 7
Joined: Thu Oct 15, 2009 8:19 am

Top

Postby desuvinodkumar » Fri Oct 16, 2009 6:06 am

HI irfan ...

See this link ....

There are some limitation of uploading video size ....

checkout this link '

http://www.google.com/support/forum/p/y ... 81d6&hl=en
Vinod...
User avatar
desuvinodkumar
Senior Developer
Senior Developer
 
Posts: 102
Joined: Mon Mar 23, 2009 6:51 am
Location: India

xml parsing

Postby hPushpa18 » Fri Nov 06, 2009 6:34 am

Hi Vinod,


i have my project attached its not parsing cc.xml file can u plz help me with this its urgent plz

Thanks,
pushpa
Attachments
XMLParsingDemo3.rar
(317.5 KiB) Downloaded 165 times
hPushpa18
Junior Developer
Junior Developer
 
Posts: 14
Joined: Mon Nov 02, 2009 11:08 am
Location: Bangalore

Postby desuvinodkumar » Fri Nov 06, 2009 7:09 am

HI Puspha ,

try this code i modified u will get the xml on the screen.......

if any problem are there means just post a message..
Attachments
XMLParsingDemo3.rar
check mofied xml parsing from Sdcard
(318.15 KiB) Downloaded 259 times
Vinod...
User avatar
desuvinodkumar
Senior Developer
Senior Developer
 
Posts: 102
Joined: Mon Mar 23, 2009 6:51 am
Location: India

Postby padde » Fri Nov 06, 2009 9:16 am

Could you post ur results?
I think SAX should clearly outperform DOM but HttpClient vs. URLConnection i really have no clue.
And by the way.. pleeeeaaaase use the code tags next time.. apart from that thanks for your work :D
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Postby desuvinodkumar » Fri Nov 06, 2009 10:31 am

HI padde,

Here find the results of Sax And Dom parsers efficiency..........
Attachments
reultdom.png
Results Of DOM Parser
reultdom.png (22.42 KiB) Viewed 8855 times
resultsax.png
Results of SAX Parser
resultsax.png (22.37 KiB) Viewed 8854 times
Vinod...
User avatar
desuvinodkumar
Senior Developer
Senior Developer
 
Posts: 102
Joined: Mon Mar 23, 2009 6:51 am
Location: India

Postby padde » Fri Nov 06, 2009 11:14 am

Wow.. thats a nice result.. DOM is really not designed for huge parsing jobs.
But its superior to SAX when it comes to parse designated parts of a file or
editing and so on.

There is a third XML parsing factory named XMLPullParser. Have you ever benchmarked this
parsing concept?

Last question.. what were the results on HttpClient vs. URLConnection? Both pictures show
the same number.. or is there simply no difference speedwise?


Thanks again for your work :!:
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Postby desuvinodkumar » Fri Nov 06, 2009 11:35 am

HI

If We go for HttpClient and URLConnection

Http will gives results more efficiently compare to URL connection, in the above screen both results are from HttpClient only.
Vinod...
User avatar
desuvinodkumar
Senior Developer
Senior Developer
 
Posts: 102
Joined: Mon Mar 23, 2009 6:51 am
Location: India

Postby shishir.bobby » Sat Feb 27, 2010 1:46 pm

i m not getting the output as u r showing here.

just a screen with a buttun,saying parse



m i doin anything wrong?



regards
shishir.bobby
shishir.bobby
Experienced Developer
Experienced Developer
 
Posts: 76
Joined: Thu Apr 09, 2009 11:41 am

Re: URLConnection VS HTTPClient & SAX VS DOM Performance ..

Postby dbhasin » Wed Jul 07, 2010 8:34 am

I'm using URLConnection to connect to the main server. The server implements digest authentication. If I connect to the server with java library, the connection is successful. But if I use the same code for android, the connection is rejected for the reason - username and password do not match.

Here is the code for my Java project:

Code: Select all

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;

public class Connect {

   static StringBuilder sb;

   public static void main(String args[]) {
      String strURL = "http://hostserver/";
      final String username = "username";
      final String password = "password";

      Authenticator.setDefault(new Authenticator() {
           protected PasswordAuthentication getPasswordAuthentication() {
               PasswordAuthentication pa = new PasswordAuthentication (username, password.toCharArray());
               System.out.println(pa.getUserName() + ":" + new String(pa.getPassword()));
               return pa;
            }
           });
      BufferedReader in = null;
      StringBuffer sb = new StringBuffer();

      try {
         URL url = new URL(strURL);
         URLConnection connection = url.openConnection();
         in = new BufferedReader(new InputStreamReader(connection
               .getInputStream()));

         String line;

         while ((line = in.readLine()) != null) {
            sb.append(line);
         }
      } catch (java.net.ProtocolException e) {
         sb.append("User Or Password is wrong!");
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            if (in != null) {
               in.close();
            }
         } catch (Exception e) {
            System.out.println("Exception");
         }
      }

      System.out.println("The Data is: " + sb.toString());

   }
}




The above code works fine and I'm able to connect to my host server which is implementing digest authentication. I'm unable to use the same code for Android to connect. Here is my android code:

Code: Select all

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class Connect extends Activity {
   static StringBuilder sb;

    @Override
   public void onCreate(Bundle savedInstanceState) {
       
        super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         
         String strURL = "http://hostserver/";
      final String username = "username";
      final String password = "password";
      Authenticator.setDefault(new Authenticator() {
           protected PasswordAuthentication getPasswordAuthentication() {
               PasswordAuthentication pa = new PasswordAuthentication (username, password.toCharArray());
//               System.out.println(pa.getUserName() + ":" + new String(pa.getPassword()));
               return pa;
            }
           });
      BufferedReader in = null;
      StringBuffer sb = new StringBuffer();

      try {
         URL url = new URL(strURL);
         URLConnection connection = url.openConnection();
         in = new BufferedReader(new InputStreamReader(connection
               .getInputStream()));

         String line;

         while ((line = in.readLine()) != null) {
            sb.append(line);
         }
      } catch (java.net.ProtocolException e) {
         sb.append("User Or Password is wrong!");
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            if (in != null) {
               in.close();
            }
         } catch (Exception e) {
            System.out.println("Exception");
         }
      }

      Log.d("DATA", sb.toString());

   }       
    }



If the same code works for Java, it should also work for Android.

The code loops in the Authenticator as it finds username and password not matching in the Android code for some reason which in fact are correct. The code runs perfect for Java project.
dbhasin
Freshman
Freshman
 
Posts: 3
Joined: Wed Jul 07, 2010 8:14 am

Top
Next

Return to Advanced Tutorials

Who is online

Users browsing this forum: No registered users and 5 guests