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.
Related
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();
}
I have a Python/Django server that is the API for a web service.
I'm building an Android application that will communicate with the API and authenticate users, and enable them do all pulls/pushes from the server.
My trouble is with the particular communication with the server. Currently I use my WiFi network, and run the server like so python manage.py runserver 192.168.1.3:8000 so that it is available to any test device on my LAN.
The API is written so it returns http status messages with every response, so that I can tell the success or failure of a request before parsing the JSON reply.
On my Android side, I have used HttpURLConnection because it has the getHeaderField(null) method that I use to pick the http status message from the response. I get a status message 200 [success] when I 'ping' my server - this is a sort-of proof of concept.
My real issue is authentication. My API requires I send it a JSON with data, and it returns a JSON response [with an http status message in the head].
I can't seem to figure out how to do this. The JSON action I've seen around the interwebs are merely picking, or posting.
I am wondering how I can POST and pick up a response from the server.
Extra information
- Server supports HEAD and GET and OPTIONS.
- Assuming server home is 192.168.1.3, user login/register would be in 192.168.1.3/user, events would be in 192.168.1.3/events and so on..
- This was the closest I got to figuring out a solution, but not quite..
CODE from the AsyncTask
protected JSONObject doInBackground(String... params) {
publishProgress(true);
/*Create a new HttpClient and Post Header*/
JSONObject result=null;
HttpClient httpclient = new DefaultHttpClient();
try {
URL url = new URL(cons.PROTOCOL,cons.SERVER,cons.PORT,"/user");
HttpPost httppost = new HttpPost(url.toURI());
HttpResponse response =null;
/*Add your data*/
JSONObject j1=new JSONObject();
JSONObject json=new JSONObject();
j1.put("username", "test");
j1.put("email","test#test.com");
j1.put("password","password");
j1.put("first_name","John");
j1.put("last_name","Doe");
json.put("user",j1);
json.put("mobile_number","256774622240");
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
/*Execute HTTP Post Request*/
response= httpclient.execute(httppost);
Log.i("jazz","It's ALIVE!!!!!");
Log.i("jazz",response.getStatusLine().toString());
} catch (ClientProtocolException e) {
/* TODO Auto-generated catch block*/
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
If your are building your HttpPostRequest well, and you only want to know how to attach JSON, here you are a possible solution for it:
StringEntity formEntity = new StringEntity(yourJsonObject.toString());
yourPostRequest.setEntity(formEntity);
I hope this helps!
PS:In addition, let me recommend you the use of this component:
https://github.com/matessoftwaresolutions/AndroidHttpRestService
I've used it in an Android app that is connecting to a python server API and it makes http request easier for your Android client.
Okay, so I'm now answering my own question :D
The issue was with the path variable in the URL string.
This is the format of one of the URL constructors based on this document.
URL(String protocol, String host, int port, String file)
Since I am posting the JSON to the /user path, that's the one I insert into the constructor as the directory.
So, my URL was formed like so:
URL url= new URL("http",cons.SERVER,cons.PORT,"/user/");
My mistake in the beginning was using /user instead of /user/
but other than that, the URL structure and connections are all alright.
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 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!
I am new to the client-server side programming so my question might be basic.
Basically, I am trying to send data in JSON format from android to a Django server. The code for sending the data is the following:
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8000/androidweb/edit/");
JSONObject j = new JSONObject();
try {
j.put("name", "cdfe");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nameValuePairs.add(new BasicNameValuePair("year", j.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}catch(Exception e) {
//catch the exception and print it
}
So my intention is to basically call the url mentioned in code. I added the url to Django urls.py so I can use the views.py class to store the JSON data I entered above in a sqlite database table, which contains only one field called "name". However, I don't know if my approach is right. Most code samples I have seen pass the data to a php file, so I was wondering if it is possible to do it through a python class, views.py?
If it is possible, can you please give me a code sample to be implemented in "views.py" of how to capture JSON data sent from the above code and store it in a table with a "name" field?
Thanks!
Data sent via POST is available via request.POST. Try examining request.POST['year'].