I know that this is a duplicate Question. But i didn't get the proper answer. My question is that. I have some data and i want to convert that data into xml and i want to send this xml with HttpPost request. When This Post request is executed then it give me data in xml format. then i want to parse the xml data. Please tell me the best way to do it. I have read Some tutorial but I haven't get proper answer. is there no other way to convert object value into xml accounting to the class field Like marshaling and unmarshaling in java please tell me the answer. Thanks in advance. I have read some example here are some links. click here and here
Simple example for XML parser using HTTP POST,
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();
}
Related
I have to request on server in form of an xml and get the response. Currently I am getting the xml not correct error. Don't know where it is wrong or my way is not correct. Below is my Xml and code I am trying.
XML:
<txn><ssl_merchant_id>893</ssl_merchant_id>
<ssl_user_id>page</ssl_user_id><ssl_pin>3472</ssl_pin>
<ssl_test_mode>false</ssl_test_mode><ssl_transaction_type>ccsale
</ssl_transaction_type><ssl_card_number>1234567890123456
</ssl_card_number><ssl_exp_date>1617</ssl_exp_date><ssl_amount>
</ssl_amount></txn>
Code I have tried:
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://demo.myvirtualmerchant.com/VirtualMerchantDemo/processxml.do");
try {
StringEntity se = new StringEntity( "<txn><ssl_merchant_id>893</ssl_merchant_id>"+
"<ssl_user_id>page</ssl_user_id><ssl_pin>3472</ssl_pin>"+
"<ssl_test_mode>false</ssl_test_mode><ssl_transaction_type>ccsale"+
"</ssl_transaction_type><ssl_card_number>1234567890123456"+
"</ssl_card_number><ssl_exp_date>1617</ssl_exp_date><ssl_amount>1.00"+
"</ssl_amount></txn>", HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppost);
String response_string = EntityUtils.toString(httpresponse.getEntity());
Log.d("request", response_string);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The response which I got is below
<?xml version="1.0" encoding="UTF-8"?>
<txn><errorCode>6042</errorCode><errorName>Invalid Request Format</errorName><errorMessage>XML request is not well-formed or request is incomplete.</errorMessage></txn>
Please suggest me something how to get rid off this issue. I heard about SOAP but don't know how to use that. Any help is appreciated.
If you are sure that your XML is what the server expects, I suggest trying to use RequestMaker to see if the problem is really Android related. You can also modify encoding and HTTP header elements to test various options.
I think that your intention is to use SOAP for a Web service request, but your XML fragment is definitely not SOAP! Find here a step by step guide to calling a SOAP Web service: LINK
I have a sample url like this:
http://www.sample.com/mobile.cgi?action=login&json_request={"user":{"name":"a","pass":"123","gender":"m","age":"25"}}
I can basically use webview.loadurl to send data to the server, but the point is...I cant get response from the server. I'm new to json. Is there any way that I can post json using the regular way? like HttpPostmaybe? and be able to get response properly.
Thanks!!
If you just wish to post JSON using HTTP and get a response back, there are many posts of stackoverflow which will help you answer that. Check How to send POST request in JSON using HTTPClient? question. I think this question answers what you are trying to say. Hope this helps you. If you have any specific concern you can always comment.
Update
As you said that you already have keys and corresponding values in addition to URL.
The first step would be to create a JSON Object. Convert it to string and then you can send it using HTTPClient and get the response back. Something like:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/");
try {
// Add your data
JSONObject user = new JSONObject();
user.put("Name", "a");
user.put("pass", "123");
// Create StringEntity
StringEntity se = new StringEntity( user.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
You can check links like this to see further exact format. I wanted to tell you the method as to how you can proceed. Hope this helps.
I'm trying to increase my knowledge to Android and trying to code a small app for my personal needs.
I'm trying to post data via the HTTP Post method on a test server.
The request is sent ok, but now, I'm trying to display the response, which is an HTML page with the dump of my request.
Here is an extract of my code, it is basically a few EditText fields, and button that sends the request.
The following code is the listener for that button.
validateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://posttestserver.com/post.php?dump&html&dir=mydir&status_code=200");
try {
// Gathering data
String value01 = nb01Spinner.getSelectedItem().toString();
String value02 = nb02EditText.getText().toString();
String value03 = nb03EditText.getText().toString();
String value04 = nb04EditText.getText().toString();
// Add data to value pairs
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(04);
nameValuePairs.add(new BasicNameValuePair("test01", value01));
nameValuePairs.add(new BasicNameValuePair("test02", value02)); //
nameValuePairs.add(new BasicNameValuePair("test03", value03));
nameValuePairs.add(new BasicNameValuePair("test04", value04));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I'm not sure if I need to create another Activity or not... I suppose I also have to create a webview aswell, but I'm a bit lost. For now the "raw" HTML would be fine, but afterwards I will need to parse the data, and extract only the strings I need.
So I would need help (an a good and simple example !)
Thank you.
String ret = EntityUtils.toString(response.getEntity());
Maybe this will help?
Very simple approach is Take textview the way you have taken button widget. and what ever response you got set in the textview. you will be able to see the response. else use the Log to log your response in the logcat.
This is how you get the Http response :
byte[] buffer = new byte[1024];
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.booom.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("params","1"));
//.......
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
buffer = EntityUtils.toString(response.getEntity()).getBytes();
I am using:
Log.d("log_response", response.getStatusLine().toString());
I have just a curiosity question. I have an HttpPost request in Android that looks something like this:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(getString(R.string.url));
//This code does not work
HttpParams params = new BasicHttpParams();
params.setParameter("type", "20");
post.setParams(params);
try {
HttpResponse response = client.execute(post);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
On my server side, I have a servlet that listens for requests and parses the parameters:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Enumeration en = request.getParameterNames();
while (en.hasMoreElements()){
System.out.println(en.nextElement());
}
}
When I execute this code, the servlet does not see any parameters at all. But if I replace the whole "parameter" chunk with this code:
//This code works
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("type", "20"));
try {
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
My servlet can parse parameters. It's not a problem, I'm just going to use the entity but my question is, why can't my servlet getthe parameters from the first code chunk? What's wrong with setParams? Why can the servlet see parameters if I make them an entity?
In HTML when we have something like "http://host/path?user=uname&passwd=pass", we call the part (user=uname&passwd=pass) after the question mark "form data".The "form data" can be attached to the end of the URL after a question mark (as above), for GET requests, or sent to the server on a separate line, for POST requests.The "form data" are split to parameters. The parameters are separated by & when we use GET.
In our case the HttpPost and HttpGet classes extend the AbstractHttpMessage which implements the setParams method. This method is same for GET and POST but does the job only for GET! In the case of GET the parameters are put in the URL. In the case of POST you need to set the entity for the parameters to be on a "separate line".
On the server side when using servlets the getParameters is clever enough to find the parameters for GET and POST.
Thats why on the server side we do not need to change the code for getting the parameters!
Hope I helped!
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?