Friday, July 29, 2011

reading response from URL using java in android app

recently, while working on one android app, i came across the situation where i need to get response from the file which is located on web. means i have one URL of file which has response code like "done" and "error"!

so i need to get that "done" if certain operation is success, if operation fails i ll receive "error".

so how to do that in java?

* first you need to import "java.net.*;" package in your source file which has "URL" class.

* create object of URL class

URL url = new URL("http://someurl.com/auth.php?email="+uname+"&password="+pass);

(in my case each time i need to send user credentials, you can see "uname" & "pass" are passed eachtime dynamically, if credentials matched, the response i will get is "done", if it fails i will get "error")

*create object of "BufferReader" class.

BufferedReader in = new BufferedReader(
new InputStreamReader(
url.openStream()));


* yay! your r done with the code! just create one variable to hold input stream from the file. and create another variable to compare result of input stream.

String inputLine;
String isdone="Done";


* just run one while loop to fetch content from the file. ;)

while ((inputLine = in.readLine()) != null)
{

if(inputLine.compareTo(isdone) == 0)
{
//Trigger an action if response is "Done"
}
else
{
//Trigger an action if response is "Error"
}
}


for further reading refer below articles:

http://download.oracle.com/javase/tutorial/networking/urls/readingWriting.html

http://download.oracle.com/javase/tutorial/networking/urls/readingURL.html


adios !

No comments:

Post a Comment