How to call a web service from android application? - android

I have no idea about how to call a web service from Android application . I also want to use trulia web service to get data from it .
So please help me.

I dont know what trulia is, If you want to use a SOAP webservice, you should use KSOAP2. Google it and you will find alot of tutorials how to use it.
There are alot of pepol explain it good.
Are KSOAP2 not for you?
Check out HTTPClient for android. here is a good one for that http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
Now, google and u find ur answer!
GL !

You can use HttpClient to connect with the webservice/webpage/remote-data.
Here is a sample code using that you can connect webservice from Android application
try {
HttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(Url);
HttpResponse response = client.execute(method);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_OK) {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = responseHandler.handleResponse(response);
return responseBody;
}
return null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}

Related

NetworkOnMainThreadException while executing HTTP Request

I searched like the whole internet but no answer could help me.
I'm trying to get a data string out of an MySQL database but just get this 'andoid.os.NetworkOnMainThreadException' error. Could anyone help me?
Here is my Code:
public String getInformationForBarcode(String barcode) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.example.com"); // Yes, i changed this in live code to my url with data in it
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost,
responseHandler);
return response.trim();
} catch (Exception e) {
System.out.println("ERROR : " + e.toString());
return "error";
}
}
Yes, I set the
<uses-permission android:name="android.permission.INTERNET" />.
All i get is the error message in LogCat :(
Hope one of you can help me!
Thanks for answering.
When you try to make connections to database it's better to do that in another thread to avoid app crash because such actions can take long time. You can use AsyncTask to perform those actions in the background. Check out the developers site for more information about the task http://developer.android.com/reference/android/os/AsyncTask.html

Using webservices in android

I have the following site http://www.freewebservicesx.com/GoldSpotPrice.aspx which provides a webservice api. As i am extremely new to soap and rest i have absolutely no clue about how to call this service and use it in android. Could someone please tell me how to do it.
You can make HTTP requests using either HttpURLConnection or HttpClient. Example of using HttpClient for a RESTful web service:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.mywebsite.com/webservice");
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
ByteArrayOutputStream out = new ByteArrayOutputStream();
entity.writeTo(out);
out.close();
String responseStr = out.toString();
// process response
} else {
// handle bad response
}
Otherwise, if you're working with a SOAP web service, I would recommend using ksoap2
Use the following url to refer:::
Using ksoap2 for android, and parsing output data...
ksoap2-android - HowToUse.wiki.....
ksoap2-android
Use this LINK it has a sample the suits your requirement.
also LINK

Android HttpPost data

I am trying to send data to my server using HttpPost via the following code.
private boolean FacebookLogin(String url) {
boolean isDataSend = false;
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("data", FacebookData()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse res = client.execute(request);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String bufstring = EntityUtils.toString(res.getEntity(),
"UTF-8");
isDataSend = true;
}
} catch (Exception e) {
}
return isDataSend;
}
Is there any way i can have a look at how the $_POST looks on the server end. so that it will be easier for me to code the server part.
You can write the received $_POST on a file. Sometimes I do that. It's not the most elegant solution, but it works fine.
Try using a http proxy (e.g. Fiddler) for debugging, it helps a lot in these cases. You can set up an emulator to use this proxy for network communications, so you can inspect the messages sent and received. Check out the emulator docs on how to configure it to use a proxy.

How to improve my Rest Calls on Android?

I am making an app for Android. I like to make the rest calls as quick as possible. When I get my results as XML it takes 5 seconds (!) to get a simple xml like this:
<souvenirs>
<souvenir>
<id>1</id>
<name>Example 1</name>
<rating>3.4</rating>
<photourl>/images/example.jpg</photourl>
<price>3.50</price>
</souvenir>
<souvenir>
<id>2</id>
<name>Example 2</name>
<rating>2.4</rating>
<photourl>/images/example.jpg</photourl>
<price>8.50</price>
</souvenir>
</souvenirs>
So I tried it with JSON. But that takes also about 5 seconds to retrieve.
I load the XML in android with the following code:
URL url = new URL("http://example.nu?method=getAllSouvenirs");
URLConnection conn = url.openConnection();
long t=System.currentTimeMillis();
InputStream ins = conn.getInputStream();
Log.d("info", String.valueOf((System.currentTimeMillis()-t)));
The log says it takes about 5000 ms to get the inputstream.. Is there any way to speed this up? does anybody knows which technique the Android Market uses? This loads way faster than my app..
Thanks in advance! :)
When you try to get the data "manually" - via browser or via other means (wget, curl) how long does it take there.
On Android you also should take the mobile network into consideration that is usually significantly slower than for a desktop computer. Also latencies are bigger.
To me this sounds a lot like issues in the backend (e.g. trying to resolve the IP of the client and thus taking lots of time).
use Apache HttpClient instead of URLConnection:
Apache http client or URLConnection
EDIT(2012-02-07): no longer true on newer android platform please read: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
Maybe that is how it is implemented and you can't do nothing. That is my guess.
My opinion is to do all connection based stuff on your own thread (to put in in background) and in foreground (main UI thread) entertain user. :)
I have played a little bit around this and it works fast enough for me... Here is my code:
private static HttpResponse doPost(String url, JSONStringer json) {
try {
HttpPost request = new HttpPost(url);
StringEntity entity;
entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8");
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
request.setEntity(entity);
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
return response;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
And somewhere else I call that method like:
HttpResponse httpResponse = doPost(url, json);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
It works fine for me...

Android, send and receive XML via HTTP POST method

There is a relevant question, but I could not get the answer clearly.
I would like to POST a short xml code
<aaaLogin inName="admin" inPassword="admin123"/>
to a specific URL address over HTTP. The Web service will send me back a XML code. The important part is that I will parse the received XML, and I want to store that as a file.
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.192.131/"); //URL address
StringEntity se = new StringEntity("<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>",HTTP.UTF_8); //XML as a string
se.setContentType("text/xml"); //declare it as XML
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient .execute(httppost);
tvData.setText(httpResponse.getStatusLine().toString()); //text view is expected to print the response
there is something wrong with receiving the response. Besides, I did not write anything to save the received XML as a file. Can someone write a code snippet?
Ok, I have figured out soon after I posted this question.
This code here works fine:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.192.131/");
try {
StringEntity se = new StringEntity( "<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>", HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
tvData.setText(EntityUtils.toString(resEntity));
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can get the content of the response using:
String responseXml = EntityUtils.toString(httpResponse.getEntity());
You can then write this to a file using something like this.
there is something wrong with receiving the response
Since you havn't said what is wrong with receiving the response it's somewhat difficult to help you with this point.
Why not use Spring RestTemplate in Spring for Android?

Categories

Resources