I tried this android code for send json objects to my website
HttpPost httppost = new HttpPost(url);
JSONObject j = new JSONObject();
j.put("name","name ");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String format = s.format(new Date());
nameValuePairs.add(new BasicNameValuePair("msg",j.toString() ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
And this php code
<?php
$msg=$_POST["msg"];
$filename="androidmessages.html";
file_put_contents($filename,$msg."<br />",FILE_APPEND);
$androidmessages=file_get_contents($filename);
echo $androidmessages;
?>
It will show me {"name":"name "}
but if i use
httppost.setHeader( "Content-Type", "application/json" );
it will show nothing.I have no before experince about json object post but i think something went wrong.I want to send some user information to my website and display it in web page can you please tell me what i need to change to overcome this problem
Thank you
Finally i got the answer
$msg=json_decode(file_get_contents('php://input'), true);
$filename="androidmessages_json.html";
file_put_contents($filename,$msg['name']."<br />",FILE_APPEND);
$androidmessages=file_get_contents($filename);
echo $androidmessages;
It depends how you want to pass the data to your PHP-script.
If you want to get the JSON as a string in one variable (and maybe others in addition), then you should not use the content-type "application/json". If you want to only post the JSON without any variable, you can do the following instead:
HttpPost httppost = new HttpPost(url);
JSONObject j = new JSONObject();
j.put("name","name ");
httppost.setEntity(new StringEntity(j.toString());
httpclient.execute(httppost);
As you can imagine from the code you do not have the JSON in one POST-var only but in total.
Related
When sending the POST request using UrlEncodedFormEntity which takes List as input parameter along with the key, my request gets converted in the form of [key={json}] .
But the request i want to send should be in the form of key={json} , i.e not as List.
So, is there any alternative for the given method when using POST?
notes: webservice is working fine , and since it is json ,i cannot use Soap .
i ve tested it using POSTman and webservices are WCF(if thats of any use..)
if any code is required , please mention it.
Thanks in advance.
Edit code:
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(URL);
List<NameValuePair> value=new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("data",string));
//here it passes as List and here is where i want an alternate method
// by which i can send parameter as JSONobject
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse response = client.execute(request);
HttpEntity entity2 = response.getEntity();
if(entity2.getContentLength() != 0) {
Reader tapReader = new InputStreamReader(response.getEntity().getContent());
char[] buffer = new char[(int) response.getEntity().getContentLength()];
tapReader.read(buffer);
tapReader.close();
JSONObject tapJsonObj = new JSONObject(buffer);
first I'm trying to be able to send a HttpResponse with parameters such as:
http://www.syslang.com/frengly/controller?action=translateREST&src=en&dest=iw&text=good&email=YYY&password=XXX
the code looks something like this:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.syslang.com/frengly/controller");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("src", "en"));
pairs.add(new BasicNameValuePair("dest", "iw"));
pairs.add(new BasicNameValuePair("text", "good"));
pairs.add(new BasicNameValuePair("email", "YYY"));
pairs.add(new BasicNameValuePair("password", "XXX"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
the API structure is available at http://www.frengly.com/ (under the API tab) and has a total of 5 parameters (src, dest, text, email, password).
so far every time I tried to call
HttpResponse response = httpClient.execute(httpPost);
I keep getting an IO Exception :(
After that I should get something like this structure:
-<root>
<text>good</text>
<translation>טוב</translation>
<translationFramed>טוב|</translationFramed>
<missing/>
<existing>good,</existing>
<stat>1/1</stat>
</root>
I think I'll handle this part to build XML and parse it as I need
p.s: I checked
Android, send and receive XML via HTTP POST method
and many other links, which didn't help me a lot.
let me know if any code lines from my application needed...
Thanks in advance.
You don't need to POST.
You need to GET instead.
// Construct your request here.
String requestURL= "http://www.syslang.com/frengly/controller?action=translateREST&src=en&dest=iw&text=good&email=YYY&password=XXX"
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(requestURL);
HttpResponse response = httpClient.execute(httpGet);
And also internet permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<application
....
....
I want to post to this url
http://abc.com/Registration.aspx?MailID=PickUp&UserName=as&PickUpTime=19191919&Notes=bla&DeviceId=0000
HttpPost httppost = new HttpPost("http://abc.com/Davis/Registration.aspx");
httppost.setHeader("MailID","MailID=PickUp");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//nameValuePairs.add(new BasicNameValuePair("MailID","PickUp"));
nameValuePairs.add(new BasicNameValuePair("UserName","as"));
nameValuePairs.add(new BasicNameValuePair("PickUpTime",date));
nameValuePairs.add(new BasicNameValuePair("Notes",note));
nameValuePairs.add(new BasicNameValuePair("DeviceId",deviceID));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Also how can I know what url I am passing . How can I log it ?
Are you sure MailID should be in the header? From the wording of the question, it looks as if all values are in the query string (in the URL past the ? mark). But then why would you need POST for that; a GET would be sufficient.
And passing data, like MailID, in headers is almost unheard of. Querystring and POST form, those are the most popular places.
So first figure out the interface of the server page. Does it expect GET or POST (or either)? Then place the fields into the right place - either into the URL (by string concatenation), or into the entity.
Oh, and the URL you're passing is http://abc.com/Davis/Registration.aspx. Neither setHeader() nor setEntity() modifies the URL per se.
I am trying to create an HTTP POST request in android where I pass "username" and "password" as POST variables.
I have code that works under most circumstances. However when the password contains the "#" symbol it no longer works.
Here is my code
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost post = new HttpPost(url);
List<NameValuePair> postData = new ArrayList<NameValuePair>();
postData.add(new BasicNameValuePair("username", "the_username"));
postData.add(new BasicNameValuePair("password", "the_password"));
post.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
HttpResponse response = httpClient.execute(post);
If "the_password" contains an #, such as "the_password#" then I'm not sure what the POST sends over the wire, but I get an error from the server.
The documentation indicates that certain special characters have to be escaped, but I'm not what API call to use to do that - and I have had no luck trying to manually escape the characters in my hard coded string.
Further more if I replace the following line:
post.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
with
post.setEntity(new StringEntity("username=the_username&password=the_password#", HTTP.UTF_8));
Then everything works - but this isn't a great solution because username and password are user entered and I'm unsure as to how that will work if they pass in a string with ampersand (&) or equals(=) in it
Any thoughts??
Are you sure your server correctly handles URL-escaped parameters?
If I run this:
List<NameValuePair> postData = new ArrayList<NameValuePair>();
postData.add(new BasicNameValuePair("username", "the_username"));
postData.add(new BasicNameValuePair("password", "the_password#"));
String urlencoform = EntityUtils.toString(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
String directstring = EntityUtils.toString(new StringEntity("username=the_username&password=the_password#", HTTP.UTF_8));
I get:
urlencoform = "username=the_username&password=the_password%40"
directstring = "username=the_username&password=the_password#"
So this means it "works" with your server if you're sending unencoded parameters. This can't be good.
Any change to check what the server is receiving and how it does/does not handle it?
import org.apache.http.message.BasicNameValuePair;
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1970"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
My Questions...
What does BasicNameValuePair class does?
What does this piece of line do
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
What does is = entity.getContent(); do? and can i pass more than one value in BasicNameValuePair class. Can i entirely pass a VO instead of this.
Like the below ...
nameValuePairs.add(new BasicNameValuePair("year","1970","sas","saassa","sas","asas"));
BasicNameValuePair is an object, specifically a container to holds data and keys.
For example if you have this data:
Name: Bob
Family name: Smith
Date of birth: 10/03/1977
then you would store this data as:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","bob"));
nameValuePairs.add(new BasicNameValuePair("family name","Smith"));
....
As you see you choose a key ("name") and data to be stored as linked to the key ("bob"). It's a type of data structure used to speed up and make easier to store this kind of informations.
On the other end you need a tool to use this data:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
this code can be divided in 4 parts:
httppost.setEntity: Is a method that take an url as argument, and tries to retrieve data (HTML or what is stored on that page) from that url, using the HTTP Post method.
new UrlEncodedFormEntity: Is a method that trasform key-data value pair in something intelligible by an http server.
it use the convention: &key=input, which one of the most used, but remember that there more ways to do it.
nameValuePair: is the data you stored before. In this case it has key the possible input forms in the html, identified by the "input name=" tag. As data it has the value that you want to give to the forms.
is = entity.getContent();: HttpEntity is an abstraction to help you handle the possible result. If the web site is unreachable or the connection is down, HttpEntity will inform you. getContent() is the method you use the retrieve the body of the Http result, i.e.: the html that the webserver sent you back, as a inputstream. If the request wasn't succesfull it will give you a null value.
BasicNameValuePair accept only couplets, so you'll have to cast it multiple times and everytime add it to the arraylist.
You can't cast it to more than two values, as they would be meaningless for the (key, value) representation of data.
Hope it helped.
In the end you're doing a http POST request with the field "year" having the value "1970".
Just like a webform posting that year would.
A bit extra:
The BasicNameValuePair looks quite aptly named: Its a very simple (basic) group of two things (pair) that serve as a formfield (name) and its contents (value).
The httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); adds that combination of year and 1970 to the HttpPost object, but with encoding (so there are no 'illegal' things in there).