HTTPPOST to aspx file - android

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.

Related

json object post to php script in android app

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.

fail to send two parameters in http - post call

I trying to send two parameters to some server.
the server is responding to http-post call and the two parameters are
Int
Some Enum ( that i sending as string )
I want to send the parameters as json:
StringEntity t = new StringEntity("{ \"intValParam\":-100 , \"enumParam\":\"enumValueAsString\" }" , "UTF-8");
httppost.setEntity(t);
httppost.setHeader("content-type", "application/json");
The response that i get is 400 ( bad request )
** There is one more method that i can call that need to have one parameter ... only the int - and this method is working good - so this is not problem from the bad connection or something like that.
You should not try to add your parameters like that. Either use the method setParams from httpPost or use NameValuePair entities and encode them in your request, like that :
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", "12312"));
nameValuePairs.add(new BasicNameValuePair("sessionid", "234"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
code taken here.

BasicNameValuePair not working with # (at symbol) in value - Trying to create an HTTP POST request in Android

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?

Loop HttpPost requests

I need to access data from a webpage using several different post requests. For now I use:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://myurl");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "search"));
nameValuePairs.add(new BasicNameValuePair("ndc", ndc));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
I need to sent this request using different values for the variable ndc. Would looping this lines be a good idea? If so, how to reuse the HttpClient and HttpPost variables?
If the URL needs to stay the same, then you should only change the values that need to sent.
for (int i=0; i<ndcArray.length;i++)
{
if(i==theNumberWhenURLhasToBeChanged) //adjust this condition based on your knowledge when the url has to be changed, lets say if i > theNumberWhenURLhasToBeChanged, then change the url...
{
httppost = new HttpPost(URLs[theNumberWhenURLhasToBeChanged]);
}
nameValuePairs.add(new BasicNameValuePair("ndc", ndcArray[i]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
Note that: response will change each time, so bear in mind that you should save the response somewhere. And ndcArray[] can be replaced with any structure you want.

Can anyone explain me this code?

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).

Categories

Resources