I am creating a networking website's Application in android.I want to know how can I perform syncing ie I want to store all user contacts on websites to my android phone.
user's details will come in XML format.
Please Guide me ..
For that you have to make a web service call either by using HttpClient or by using other third-party libraries like kSoap2. But i would prefer native class instead of third-party library.
Here is a best example: http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
After making a call, you will receive a XML, after that you can parse the received XML response either by using SAX parser, Pull Parser or DOM Parser.
This is the scenario to fetch data from web to your local database.
For your info: To get response from Web:
public static InputStream getInputStreamFromWeb(String url) {
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.("GET", "Network exception", e);
}
return content;
}
Related
Currently, I'm building a Android mobile app & Python restful server services.
I found that, it makes no different, whether or not I'm using
self.response.headers['Content-Type'] = "application/json"
The following code (which doesn't specific Content-Type explicitly) works fine for me. I was wondering, in what situation, I should specific Content-Type explicitly?
Python restful server services code
class DebugHandler(webapp2.RequestHandler):
def get(self):
response = {}
response["key"] = "value"
self.response.out.write(json.dumps(response))
application = webapp2.WSGIApplication([
('/debug', DebugHandler),
], debug = True)
Android mobile app client code
public static String getResponseBodyAsString(String request) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(request);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
initHttpURLConnection(httpURLConnection);
InputStream inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
int charRead = 0;
char[] buffer = new char[8*1024];
// Use StringBuilder instead of StringBuffer. We do not concern
// on thread safety. stringBuffer = new StringBuffer();
StringBuilder stringBuilder = new StringBuilder();
while ((charRead = bufferedReader.read(buffer)) > 0) {
stringBuilder.append(buffer, 0, charRead);
}
return stringBuilder.toString();
} catch (MalformedURLException e) {
Log.e(TAG, "", e);
} catch (IOException e) {
Log.e(TAG, "", e);
} finally {
close(bufferedReader);
}
return null;
}
Content-Type specifies what's inside the response (i.e. how to interpret the body of the response). Is it JSON, a HTML document, a JPEG, etc? It is useful when you have different representations of your resources and together with Accept it's a header involved in doing content negotiation between client and server.
Different clients might need different formats. A C# client might prefer XML, a Javascript client might prefer JSON, another client could work with multiple representations but try to request the most efficient one first and then settle for others if the server can't serve the preferred one, etc.
Content-Type is very important in the browser so that the user agent knows how to display the response. If you don't specify one the browser will try to guess, usually based on the extension and maybe fallback to some Save as... dialog if that fails also. In a browser, the lack of a Content-Type might cause some HTML to open a Save as... dialog, or a PDF file to be rendered as gibberish in the page.
In an application client, not having a Content-Type might cause a parsing error or might be ignored. If you server only serves JSON and your client only expects JSON then you can ignore the Content-Type, the client will just assume it's JSON because that's how it was built.
But what if at some point you want to add XML as a representation, or YAML or whatever? Then you have a problem because the client assumed it's always JSON and ignored the Content-Type. Now when it receives XML it will try to parse as JSON and fail. If instead the client was built with content types in mind and you always specify a Content-Type then your client will then take it into account and select an appropriate parser instead of blindly making assumptions.
I need to parse XML data from a web service. But, when I am getting the data from the web service the data comes in the format of JSON (In the browser I am seeing the data as XML). So, please guide me how to get xml data into my application.
I am using the following.
In my main activity:
static final String URL = "http://nclex.testshell.net/api/resources";
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Log.e("Response is...",xml);
My xmlParser class
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
}
output response is
[{"ResourceId":1,"Title":"GRE revised General Test","Description":"The
Verbal Reasoning section of the GRE revised General
Test","Link":"http://www.ets.org/gre/revised_general/about/content/verbal_reasoning"},{"ResourceId":2,"Title":"GRE Power Pre","Description":"GRE Power
Pre","Link":"http://www.number2.com/exams/gre/companion/index.cfm?s=0"},{"ResourceId":3,"Title":"GRE Analytical Writing","Description":"GRE Analytical
Writing","Link":"http://www.mygretutor.com/tests.aspx"},{"ResourceId":4,"Title":"GATE
Architecture & Planning","Description":"GATE Architecture &
Planning","Link":"http://www.onestopgate.com/gate-sample-papers/architecture-planning/"},{"ResourceId":5,"Title":"TarGATE","Description":"GATE
to acheive your
target","Link":"http://gateforum.com/Testseries-Venue.php"},{"ResourceId":6,"Title":"TOEFL
iBT","Description":"TOEFL iBT Test Sample
Questions","Link":"https://www.ets.org/toefl/ibt/prepare/sample_questions"}]
The type or format of data you retrieved from the server using web service is totally depends on the language in which web service is implemented and the response code that web service choose to format the data..
Older web services or platforms mainly supports XML format.And the new web services uses the Json format for its light-weight.
In your case,Your web service supports both type of format(XML,Json) and it chooses the format as per the platform from which it receives the request(Mobile,Desktop).(May be it acts as a Generic Webservice).
One way to test the webservice response is to requesting it from platform browser i.e use your platform browser(Desktop or mobile) to see the response for your platform.
Finally,Answer to your question,
Change the code at your server side and make sure that it returns XML data as a response for Mobile platform(you don't have to worry about the code at your application side;all changes to be done at server side).
However,you can also convert Json to xml as,
JSONObject Jobj = new JSONObject(jsonString);
Then you can get it in XML format using the XML class, like so:
String xml = org.json.XML.toString(Jobj);
but it's not recommended as it need extra cpu time to convert Json to xml and it can be a problem if your response data is huge.
Can anyone tell me which is the best, ease and flexible method to consume web service from android? I'm using eclipse.
Since you only care about consuming a webservice, I assume you already know how to send data from the web server. Do you use JSON or XML, or any other kind of data format?
I myself prefer JSON, especially for Android.
Your question still lacks some vital information.
I personally use apache-mime4j and httpmime-4.0.1 libraries for web services.
With these libraries I use the following code
public void get(String url) {
HttpResponse httpResponse = null;
InputStream _inStream = null;
HttpClient _client = null;
try {
_client = new DefaultHttpClient(_clientConnectionManager, _httpParams);
HttpGet get = new HttpGet(url);
httpResponse = _client.execute(get, _httpContext);
this.setResponseCode(httpResponse.getStatusLine().getStatusCode());
HttpEntity entity = httpResponse.getEntity();
if(entity != null) {
_inStream = entity.getContent();
this.setStringResponse(IOUtility.convertStreamToString(_inStream));
_inStream.close();
Log.i(TAG, getStringResponse());
}
} catch(ClientProtocolException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
_inStream.close();
} catch (Exception ignore) {}
}
}
I make a request via _client.execute([method], [extra optional params])
The result from the request is put in a HttpResponse object.
From this object you can get the status code and the entity containing the result.
From the entity I take the content. The content would in my case be the actualy JSON string. You retrieve this as an InputStream, convert the stream to a string and do whatever you want with it.
For example
JSONArray result = new JSONArray(_webService.getStringResponse()); //getStringResponse is a custom getter/setter to retrieve the string converted from an inputstream in my WebService class.
Depending on how you build your JSON. mine is nested deeply with objects in the array etc.
But handling this is basic looping.
JSONObject objectInResult = result.getJSONObject(count);//count would be decided by a while or for loop for example.
You can extract data from the current JSON object in this case like:
objectInResult.getString("name"); //assume the json object has a key-value pair that has name as a key.
to parse "JSON" I recommend the following library is the faster and better.
Jackson Java JSON-processor
I am using the Jackson JSON parser as I heard it was a lot more efficient than the default Android parser. I learned how to use it off this tutorial here
http://www.mkyong.com/java/jackson-streaming-api-to-read-and-write-json/
which is great tutorial if anyone wants to learn how to use Jackson json parser.
However, I am having an issue in that I can parse data fine in Java from a URL, however when I use Jackson with Android, I get null values or the screen just shows up black for some reason.
In order to retrieve the data from the website I am using this code from here
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
Then in my parse data method
InputStream source = retrieveStream(url);
try {
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createJsonParser(source);
Then I parse data as was shown in the tutorial I linked above
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if ("Name".equals(fieldname)) {
jParser.nextToken();
this.setName(jParser.getText());
}
if ("Number".equals(fieldname)) {
jParser.nextToken();
this.setNumber(jParser.getText());
}
}
The url I am using is a dummy site set up which just has a JSON file on it which I am using to practice Jackson JSON parsing.
Now I know my parse data code is fine, as I in normal Java class, I can parse the data from the website using the code I created, and it works fine.
However if I try to use the code in Android with the code I have just shown, I just get a black screen for some odd reason. I have internet permissions enabled in manifest
Is there something wrong with the http code I have used? If so could someone show me how it should be done? And also why I am getting a black screen, I don't understand why it would show that.
Thanks in advance
Not sure if this is the problem, but your looping construct is unsafe: depending on kind of data you get, it is quite possible that you do not get END_OBJECT as the next token. And at the end of content, nextToken() will return null to indicate end-of-input. So perhaps you get into infinite loop with certain input?
I found the issue, the link was local host which could not be accessed from Emulator. Settings were changed, and can now access link, works perfectly now :D
How would one go about sending data back to server, from an android application?
I've already tried using HttpPost and posted back to a RESTful WCF service, but I couldnt get that to work (I've already created a SO question about this, without finding the solution..) - No matter what I do I keep getting 405 Method not allowed or the 400 Bad Request.. :(
I'm not asking for full code example necessarily.. just a pointer in a direction, which can enable me to send data back to a server.
It is important that the user should not have to allow or dismiss the transfer.. it should happen under the covers, so to speak
Thanks in advance
Services is the way to go. REST (I recommend this one on Android), or SOAP based. There're loads of tutorials on getting an android app communicate a service, even with .net / wcf ones.
Tho you can always just open raw sockets and send data with some custom protocol.
Edit:
Here's the doInBackground part of my asynctask handling http post communication, maybe that'll help:
protected String doInBackground(String... req) {
Log.d(TAG, "Message to send: "+req[0]);
HttpPost p = new HttpPost(url);
try{
p.setEntity(new StringEntity(req[0], "UTF8"));
}catch(Exception e){
e.printStackTrace();
}
p.setHeader("Content-type", "application/json");
String response = "";
try{
HttpResponse resp = hc.execute(p, localContext);
InputStream is = resp.getEntity().getContent();
response = convertStreamToString(is);
Log.d("Response", "Response is " + response);
} catch (Exception e){
e.printStackTrace();
}
return response;
}