I want to Parse the XML Response in my Application using a SAX PArser, I don't know how to do that, So Can anybody please giude me to the right path.
An example with a little coding or a link will be OK.
Thanks,
david
try {
HttpClient client = new DefaultHttpClient();
String getURL = <URL>;
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
mResEntityGet = responseGet.getEntity();
if (mResEntityGet != null) {
//do something with the response
content = EntityUtils.toString(mResEntityGet);
}
} catch (Exception e) {
e.printStackTrace();
}
"content" will be the string of XML format, parse it using XML pull parser.
Related
I am doing a project in android, to get the website data's into my android application.
I tried JSON but it doesn't help me to achieve my project. Please help me...
i've used this code for my project
HttpClient client = new DefaultHttpClient();
String getURL = "http://yourservername/wifi.ashx?cmd=get;1;";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
String str;
if (resEntityGet != null) {
str = EntityUtils.toString(resEntityGet).substring(2, 4); // determined the maximumum id in server
str.lastIndexOf(str);
}
} catch (Exception e) {
e.printStackTrace();
// link.setText("errorororo");
}
Im doing a simple http get,
I see on my result an incomplete response,
what Im doing wrong?
here the code:
class GetDocuments extends AsyncTask<URL, Void, Void> {
#Override
protected Void doInBackground(URL... urls) {
Log.d("mensa", "bajando");
//place proper url
connect(urls);
return null;
}
public static void connect(URL[] urls)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet("http://tiks.document.dev.chocolatecoded.com.au/documents/api/get?type=tree");
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.d("mensa",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
Log.d("mensa", "estratagema :: "+result);
JSONObject jObject = new JSONObject(result);
Log.d("mensa", "resposta jObject::"+jObject);
Log.d("mensa", "alive 1");
JSONArray contacts = null;
contacts = jObject.getJSONArray("success");
Log.d("mensa", "resposta jObject::"+contacts);
Log.d("mensa", "alive");
//instream.close();
}
} catch (Exception e) {}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.d("mensa", "linea ::"+line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
i call it with:
GetDocuments get = new GetDocuments();
URL url = null;
try {
url = new URL("ftp://mirror.csclub.uwaterloo.ca/index.html");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//URL url = new URL("http://www.google.es");
get.execute(url);
edit 1
I refer to incomplete as the response that gets truncated?
please notice in below image of response how string gets truncated,
is this because of the log size?,
but the other problem is that it doesn't parse?
thanks!
I don't know if this is going to resolve your problem but you can get rid of your method and use simply:
String responseString = EntityUtils.toString(response.getEntity());
I've had exactly the same issue for the last couple of days. I found that my code worked over WiFi but not 3G. In other words I eliminated all the usual threading candidates. I also found that when I ran the code in the debugger and just waited for (say) 10 seconds after client.execute(...) it worked.
My guess is that
response = httpclient.execute(httpget);
is an asynchronous call in itself and when it's slow returns a partial result... hence JSON deserialization goes wrong.
Instead I tried this version of execute with a callback...
try {
BasicResponseHandler responseHandler = new BasicResponseHandler();
String json = httpclient.execute(httpget, responseHandler);
} finally {
httpclient.close();
}
And suddenly it all works. If you don't want a string, or want your own code then have a look at the ResponseHandler interface. Hope that helps.
I have confirmed that this is because size limit of java string. I have checked this by adding the string "abcd" with the ressponse and printed the response string in logcat. But the result is the truncated respose without added string "abcd".
That is
try {
BasicResponseHandler responseHandler = new BasicResponseHandler();
String json = httpclient.execute(httpget, responseHandler);
json= json+"abcd";
Log.d("Json ResponseString", json);
} finally {
httpclient.close();
}
So I put an arrayString to collect the response. To make array, I splitted My json format response by using "}"
The code is given below(This is a work around only)
BasicResponseHandler responseHandler = new BasicResponseHandler();
String[] array=client.execute(request, responseHandler).split("}");
Then you can parse each objects in to a json object and json array with your custom classes.
If you get any other good method to store response, pls share because i am creating custom method for every different json responses );.
Thank you
Arshad
Hi Now I am using Gson library to handle the responses.
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
Thanks
Arshad
I cant' comment directly due to reputation, but in response to https://stackoverflow.com/a/23247290/4830567 I felt I should point out that the size limit of a Java String is about 2GB (Integer.MAX_VALUE) so this wasn't the cause of the truncation here.
According to https://groups.google.com/d/msg/android-developers/g4YkmrFST6A/z8K3vSdgwEkJ it is logcat that has a size limit, which is why appending "abcd" and printing in logcat didn't work. The String itself would have had the appended characters. The previously linked discussion also mentioned that size limits with the HTTP protocol itself can occasionally be a factor, but that most servers and clients handle this constraint internally so as to not expose it to the user.
i have this high score board in http://drymvizion.atwebpages.com/ and i want a simple way to click a button and show this content in my android application without opening browser. I am a bit new in android developing and i hope it's easy. Thanks ;)
You could use a HttpGet request to get the contents, or better use a xml parser, such as JSoup. For example:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("site.name");
try
{
get.addHeader("Accept-Charset","utf-8");
HttpResponse response = client.execute(get);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String result = "";
while ((result = rd.readLine()) != null)
{
Log.e("HttpResponse", result);
if (result.length() > 0)
{
// do something with the source
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
Have a look at WebView's
http://developer.android.com/reference/android/webkit/WebView.html
I am trying to use Google graph API (image) to show some data in the form of PIE chart. http://chart.apis.google.com/chart?chs=250x150&cht=p3&chd=t:41.86,26.00,21.78,10.36&chdl=User998|User591|User671|Others, this link gives a pie chart when viewed in browser. But, when I am trying to get the response using HttpClient, I am getting illegal character error. I am using following code to get the response
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
String chartUrl = "above url";
//Here, I am getting illegal character error.
HttpGet getRequest = new HttpGet(chartUrl);
getRequest.setHeader("Content-Type", "image/png");
httpResponse = client.execute(getRequest);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
bmImg = BitmapFactory.decodeStream(instream);
instream.close();
}
}
catch(Exception e)
{
//TODO
}
Can anyone tell me how to fix this issue?
Thanks,
Ashwani
The character in question is |, you can work around by using %7C instead in the URL and it should work.
I am creating an Android application that connects to the Fogbugz XML API (sends a request to the API, receives back an XML file). Right now, I am creating a service that will handle these requests, and parse each in order to access usable information. What would be the best way to do this? If I am getting an inputStream, should I use the SAX parser?
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("My URL THAT RETURNS AN XML FILE");
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String responseString = "";
String temp;
while ((temp=bufferedReader.readLine()) != null)
{
responseString += temp;
}
if (entity != null) {
entity.consumeContent();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I suggest that you use some XML DOM library like XOM or Dom4j. It will be much easier for you to work with tree structure than with SAX events. Personally, I use XOM in Foglyn -- FogBugz for Eclipse plugin. You can pass InputStream directly to your SAX/XOM/Dom4j parser, there is no need to build string first. Furthermore, make sure you use correct encoding ... your code is broken in this regard. (When you pass InputStream to your parser, this is handled by parser. In XOM you can use new Builder().build(InputStream) method).
One FogBugz API hint ... when getting details about case, and you don't need events (comments), don't fetch them at all. I.e. don't put events into list of columns.