how to parse xml data from HTTPResponse in android - android

i have made an activity in android,in that i have made a multipart entity request using HttpPost,Now i am getting successfull respose also.but thing is i dont know how to get those data from response.i have tried number of links for parsing xml but with no luck.Please help me for this.how to get data from my xml respose.My code is as below:
login
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Consts.API_HOST + "/login");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("apiKey",
"JU7Jqt6X"));
nameValuePairs.add(new BasicNameValuePair("type", "xml"));
nameValuePairs.add(new BasicNameValuePair("email",
"yogesh#amarinfotech.com"));
nameValuePairs.add(new BasicNameValuePair("pwd", "123"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// xml response..!jigar...
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// end of res jigar...
System.out
.println("::::::::::::::::::::::::;;MY RESPONSE IN LOGIN ATIVITY::::::::::"
+ responseBody);
// making doc
Document doc = null;
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader sr = new StringReader(responseBody);
InputSource is = new InputSource(sr);
doc = builder.parse(is);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
} catch (Exception e) {
System.out
.println("::::::::::::::::::::::::::::MY exception in edit::::::::::::::::"
+ e.getMessage());
return null;
}
return null;
// Parsing Procedure......
Response
<?xml version="1.0" encoding="ISO-8859-1" ?>
<root>
<id>
8
</id>
<personal_title>
Mr.
</personal_title>
<first_name>
a
</first_name>
<middle_name>
b
</middle_name>
<last_name>
c
</last_name>
<email>
yogesh#amarinfotech.com
</email>
<password>
202cb962ac59075b964b07152d234b70
</password>
<mobile_number>
1234567890
</mobile_number>
<p_first_name>
</p_first_name>
<p_last_name>
</p_last_name>
<p_card_type>
</p_card_type>
<p_card_number>
</p_card_number>
<p_sec_code>
</p_sec_code>
<p_exp_month>
</p_exp_month>
<p_exp_year>
</p_exp_year>
<user_activation_key>
14164668001
</user_activation_key>
<varification>
1
</varification>
<send_mail>
0
</send_mail>
<status>
0
</status>
<register_date>
2014-11-20 23:04:14
</register_date>
<last_visit_date>
2014-11-20 23:04:14
</last_visit_date>
</root>

I got my answer by my way.Hello all for your responses but i got myy question solved by my way ,Actually all are telling me about different parsing but i want to know about the parsing from HTTP RESPONSE,So i have got my solution,here it is:
http://www.java2s.com/Code/Android/Development/getCharacterDataFromElement.htm
Thanks for this useful post.

String xml="<yourxml></yourxml>"
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/xml");
StringEntity entity = new StringEntity(xml);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);

Related

POST request always return html instead of JSON in android

I am building a simple android application where I am making a Login Page and implementing a simple POST web API. Previously it was working fine but suddenly it stops working and now it is always returning me HTML code. Below is my code,
try {
List<NameValuePair> li = new ArrayList<NameValuePair>();
li.add(new BasicNameValuePair("username", "ma#dhdh.com"));
li.add(new BasicNameValuePair("password", "123456dndjsj789"));
li.add(new BasicNameValuePair("key", "ZATXMhjHartjDTrH"));
HttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpPost httppost = new HttpPost("http://www.deal.com.lb/merchant_ws/login_ws.php");
httppost.setHeader("Content-Type", "text/html");
httppost.setHeader("Accept","application/json");
httppost.setEntity(new UrlEncodedFormEntity(li));
httpResponse = httpClient.execute(httppost);
httpEntity = httpResponse.getEntity();
String response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please tell me which code I had wrote wrong. Also this service is also working as GET request. You can try it in browser. In browser it is working properly but in Android code it is not.
Have you set header('Content-Type: application/json');
in your PHP? And have you a trace, log of Java-Code?

Blank Response when doing JSON POST from Android

I am trying to post two json encoded values to my webservice using the below code. but i am not getting any response (Just Blank Output and No errors on LogCat). However, I have tried posting the same parameters from PHP to my webservice using cURL which works great.
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
try {
json.put("name","email");
json.put("email", "email");
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept-Encoding", "application/json");
post.setHeader("Accept-Language", "en-US");
List<NameValuePair> ad = new ArrayList<NameValuePair>(2);
ad.add(new BasicNameValuePair("json", json.toString()));
post.setEntity(new UrlEncodedFormEntity(ad));
Log.i("main", "TestPOST - nVP = "+ad.toString());
response = client.execute(post);
if(response!=null) {
HttpEntity entity = response.getEntity();
output = EntityUtils.toString(entity,HTTP.UTF_8); //Get the data in the entity
}
} catch(Exception e) {
}
Try Getting your response by this
if (response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
}
You're catching Exception (the super class) without logging. If an exception of any kind occurs in your try block the code will jump to the catch without any log.
Change this:
catch(Exception e){
}
with
catch (Exception e)
Log.e("myappname", "exception", e);
}
If there is no response, you should definitely check your catch exception e, since you didn't write anything in the clause, there might be something happening but you didn't notice.

Create this string exactly in Android

I want to build 2 same products for Android and iOs.
The iOs already works, but the android doesnt, that's because of the format of the string.
in iOs this is:
NSString*jsonString = [[NSString alloc] initWithFormat:#"{\"id\":\"%#\",\"longitude\":\"%#\",\"latitude\":\"%#\",\"timestamp\":\"%#\"}", _phonenumber, longitude , latitude, stringFromDate];
And i dont know how to do this exactely like this in android. The format here is different.
What i have now is:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("id", num));
nameValuePairs.add(new BasicNameValuePair("longitude", longi));
nameValuePairs.add(new BasicNameValuePair("latitude", lat));
nameValuePairs.add(new BasicNameValuePair("timestamp", time));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
Thanks in advance, i need this by the end of the week so if you could help me, that would be greatly appreciated
i get this as an result from the iOs string:
{
"id":"0612833398",
"longitude":"-143.406417",
"latitude":"32.785834",
"timestamp":"10-10 07:56"
}
Okay, this is what my problem is.
Yes i need to send this exact string to an asp.net file on a server. But i need to know how to combine this with this: with the http post to
HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php");
before i combined this with the nameValuePPairs like this
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Create same string as you are getting in IOS by create an JosnObject as:
JSONObject json = new JSONObject();
json.put("id", "0612833398");
json.put("longitude", "-143.406417");
json.put("latitude", "32.785834");
json.put("timestamp", "10-10 07:56");
now if you make a print for json object you will get this string :
{"id":"0612833398","longitude":"-143.406417","latitude":"32.785834",
"timestamp":"10-10 07:56"}
and Post JSONObject as to server :
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php");
httppost.setHeader("Content-type", "application/json");
// Create json object here...
JSONObject json = new JSONObject();
json.put("id", "0612833398");
json.put("longitude", "-143.406417");
json.put("latitude", "32.785834");
json.put("timestamp", "10-10 07:56");
/// create StringEntity with current json obejct
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
}
To create a String you can use String.format(). In this case the syntax is very similar to Objective-C:
String s = String.format("{\"id\":\"%s\",\"longitude\":\"%s\",\"latitude\":\"%s\",\"timestamp\":\"%s\"}", num, long, lat, time);
HTTP Post goes like this:
HttpPost postMethod = new HttpPost(url);
try {
HttpParams params = new BasicHttpParams();
params.setParameter(name, value);
postMethod.setParams(params);
httpClient.execute(postMethod);
} catch (Exception e) {
} finally {
postMethod.abort();
}

Android Getting JSON return error from POST Http execution

I'm currently trying to send data via POST to a server, and the server is handling the data and appends it to a JSON file. I'm currently getting a 422 error and I've been receiving it for a while now. My question is: How do I receive that JSON error itself in Java so that I can see what the error is. All I'm seeing is a HttpResponseException and it doesn't give me anything else. Thanks for the time and help in advance.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mPath);
// Add your data
try
{
List nameValuePairs = new ArrayList(4);
httppost.setHeader("Authorization", Base64.encodeToString(new StringBuilder(bundleId).append(":").append(apiKey).toString().getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP));
nameValuePairs.add(new BasicNameValuePair("state", "CA"));
nameValuePairs.add(new BasicNameValuePair("city", "AndDev is Cool!"));
nameValuePairs.add(new BasicNameValuePair("body", "dsads is assrawstjljalsdfljasldflkasjdfjasldjflasjdflkjaslfggddsfgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfddjflaskjdfkasjdlfkjasldfkjalskdjfajasldfkasdlfjasljdflajsdfjasdjflaskjdflaksjdfljasldfkjasljdflajsasdlfkjasldfkjlas!"));
nameValuePairs.add(new BasicNameValuePair("title", "dsaghhhe fd!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
//HttpResponse response = httpclient.execute(httppost);
//int status = response.getStatusLine().getStatusCode();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
Log.v(TAG, "response: " + responseBody);
//JSONObject response = new JSONObject(responseBody);
int f = 0;
}
catch(HttpResponseException e)
{
Log.e(TAG, e.getLocalizedMessage());
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
you may send your parameters more conveniently by using predefined Json class as below:
String jsonParam = null;
try{
JSONObject param = new JSONObject();
param.put("state", "CA");
param.put("city", "AndDev is Cool!");
//and so on with other parameters
jsonParam = param.toString();
}
catch (Exception e) {
// TODO: handle exception
}
and set the post entity as:
if(jsonParam != null)
httppost.setEntity(new StringEntity(jsonParam, HTTP.UTF_8));
422 error says: Unprocessable Entity - The request was well-formed but was unable to be followed due to semantic errors
You got a problem with UrlEncodedFormEntity

Android: Http post with parameters not working

I need to create an HTTP POST request with parameters. I know there are many examples out there, I have tried using HTTPparams, NameValuePair etc but cant seem to get the correct format for the server.
Server Type: REST based API utilizing JSON for data transfer
Content-type: application/json
Accept: application/json
Content-length: 47
{"username":"abcd","password":"1234"}
I can pass these headers but I cant seem to pass these params "username","password". Here is my code:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username","abcd"));
pairs.add(new BasicNameValuePair("password","1234"));
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,"UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
I tried to debug, but cant see if entity is attached properly or not... What am I doing wrong?
Thanks in Advance.
Maaz
Try this:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
obj.put("username", "abcd");
obj.put("password", "1234");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
I'm not quite sure, from your description, but it would seem that your server expects a JSON content object instead of the data being encoded in the URL. Send something like this as the body of your post:
{"username":"abcd","password":"1234"}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username","abcd"));
pairs.add(new BasicNameValuePair("password","1234"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse response = client.execute(post);
just try this coz it works perfect for me when i am trying to HTTP post.
this will probably work for you.
assuming you already have the json object.
NOTE: (1)in the server you need to handle th request as utf-8 (also in the DB).
#SuppressWarnings("unchecked")
private static HttpResponse executePostRequest(JSONObject jsonData, String url) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
try {
httpost.setEntity(new ByteArrayEntity(jsonData.toString().getBytes("UTF8")));
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json;charset=UTF-8");
httpost.setHeader("Accept-Charset", "utf-8");
HttpResponse httpResponse = httpclient.execute(httpost);
return httpResponse;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
then in the client handle the server response like this:
String responseBody = EntityUtils
.toString(response.getEntity(), "UTF-8");

Categories

Resources