I'm new in Android development. I made an Android app for login in a website. The login page takes three inputs 'username', 'password' & 'pin'.
I've successfully passed these data using HttpPost method. See the code,
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mysite.com/api/service.php");
try {
// Add user name, password & pin
String action = "login";
EditText uname = (EditText)findViewById(R.id.txt_username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.txt_password);
String password = pword.getText().toString();
EditText pcode = (EditText) findViewById (R.id.txt_pin);
String pin = pcode.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("action", action));
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("pin", pin));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("PS", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Now i want to parse the 'ack' & 'msg' from HttpResponse which is a XML output appears after passing data to the website. See here,
<login>
<member>
<id/>
<username/>
<name/>
<ewallpoints/>
<ack>FAILED</ack>
<msg>Wrong Username and Password</msg>
</member>
</login>
Use response.getEntity().getContent() to get an input stream and process it with DOM, SAX or XPath as #tobias suggested. There are many options.
You may also get the xml string directly. Change the line
HttpResponse response = httpclient.execute(httppost);
to
String xml = httpclient.execute(httppost, new BasicResponseHandler());
Related
I am trying to insert UTF-8 characters(Like username in hindi or tamil language) in MySql with Codeigniter framework.
Here is my android side code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uploadApi);
try {
List<NameValuePair> nameValuePairs=new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("key1","विकिपीडिया"));
nameValuePairs.add(new BasicNameValuePair("key2","इण्टरनेट"));
UrlEncodedFormEntity form = new UrlEncodedFormEntity(nameValuePairs);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
and this is server side code in codeigniter:
public function create()
{
$name=$this->input->get_post("name") ;$text=$this->input->get_post("text");
$type=$this->input->get_post("type");$contact=$this->input->get_post("contact");
$mp=$this->input->get_post("mp");$mla=$this->input->get_post("mla");
$position=$this->input->get_post("position");
$config['upload_path'] = './uploads/';
$config['allowed_types'] = '*';
$config['max_size'] = '20000';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('image'))
{
$image="noimage.jpg";
echo $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
$image=$data['file_name'];
}
$data['json']=$this->uploadmodel->insert($name,$image,$text,$contact,$mp,$mla,$type,$position);
echo "Thanks for Sharing";
}
All configuration is set to utf-8 in configuration file.
error is i am getting all string like ?????????
please tell me where i am doing wrong.
Thanks
I added this line:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
Although i tried with it also before.
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
but the above runs successfully.
I am trying to send user email address and password from my android app to the db to login via POST.
On the server side, I get my data like this :
$email = $_POST['email'];
$password = clean($_POST['password'];
And on the android side I send it like so:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("some real URL");
httppost.setHeader("Content-type", "application/json");
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httppost);
......
Even when I type in valid login details, it fails and says no email address or password. Am I sending things across correctly?
I have also tried sending data across like below but didnt work. Any suggestions?
JSONObject obj = new JSONObject();
obj.put("email", email );
obj.put("password", password);
httppost.setEntity(new StringEntity(obj.toString()));
HttpPost.setEntity sets the body of the request without any name/value pairings, just raw post data. $_POST doesn't look for raw data, just name value pairs, which it converts into a hashtable/array. You can format the request such that it includes name value pairs.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("json", json.toString()));
httppost.setEntity(new UrlEncodedFormEntity(params));
And have the parameters in json object as:
JSONObject json = new JSONObject();
json.put("email", email );
json.put("password", password);
On the server side you can get the data as:
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
if( !empty($jsonObj)) {
try {
$email = $jsonObj['email'];
$password = $jsonObj['password'];
}
}
I want to make an application for a web page that needs POST login. After that I'll download an HTML page and read its tags and perform some tasks to display some information.
Before I begin, I want to know if there is a way login in to this page using POST, somehow programmatically and download the page.
this is a way to send post request:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/login.php");
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", "value"));
Httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String result = EntityUtils.toString(response.getEntity());
}
catch(Exception e)
{
e.printStackTrace();
}
you can send your information in order to login to page.!
How do I send the data to this PHP file below? I can establish the connection and send data, but can't receive the response. I need to send 3 parameters, the "op", Username and password.
switch ($_POST["op"]) {
// User Authentication.
case 1:
$UName = $_POST["UName"];
$UPass = $_POST["UPass"];
$UPass = md5($UPass);
//....Some code
// New user registration process.
case 2:
$UName = $_POST["UName"];
$UPass = $_POST["UPass"];
$UEmail = $_POST["UEmail"];
$UNick = $_POST["UNick"];
$UPass = md5($UPass);
//....Some code
}
My code so far:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://SomeUrl/login.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("1", "dan"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d(TAG, ""+responseBody);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
What am I doing wrong?
Looking at your PHP code, at a bare minimum you need to specify an op parameter. Then depending on which op you're trying to carry out, make sure you specify the other needed parameters as well. For user authentication (op = 1):
nameValuePairs.add(new BasicNameValuePair("op", "1"));
nameValuePairs.add(new BasicNameValuePair("UName", "dan"));
nameValuePairs.add(new BasicNameValuePair("Pass", "somepass"));
On a side note, you should secure the PHP service with SSL, if you are using it to process sensitive user information.
Android HTTP POST should look like this:
HttpParams httpParams=new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
// Data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("UName", "dan"));
nameValuePairs.add(new BasicNameValuePair("UPass", "password"));
nameValuePairs.add(new BasicNameValuePair("op", "1"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://SomeUrl/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
}
In your PHP code I would strongly recommend to use mysql_real_escape_string($_POST['UName']) otherwise it is easy to attack via SQL injection.
I would also recommend to use either SSL connection (HTTPS) or to send the password only hashed (MD5)
In my application I'm using outpost method to send data to web service which is in .net.Now when i send string with spaces or special characters it takes the string with e.g. test string would display like test+string.
I'm using httpDefaultClient with nameValuePair to send data...i've used UrlEncode function to encode my string but still result is the same...
Please help me...
Here is my code
//web service call
HttpClient client=new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(url2));
List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
// nameValuePairs.add(new BasicNameValuePair("CreateHotSpots", value))
nameValuePairs.add(new BasicNameValuePair("sKey",""+globalClass.getUser_key()));
nameValuePairs.add(new BasicNameValuePair("sLAKE",encodedlakename));
if(!(DragAndDropPinActivity.point.isEmpty())){
nameValuePairs.add(new BasicNameValuePair("sLAT",""+DragAndDropPinActivity.point.get(0)));
nameValuePairs.add(new BasicNameValuePair("sLon",""+DragAndDropPinActivity.point.get(1)));
}
else
{
url2=url2.concat("&sLAT="+""+myLatitude);
url2=url2.concat("&sLon="+""+myLongitude);
}
nameValuePairs.add(new BasicNameValuePair("sDesc",encodedDesc));
nameValuePairs.add(new BasicNameValuePair("sSpeciesofFish",encodedFishSpecies));
nameValuePairs.add(new BasicNameValuePair("sBaitUsed",encodedbUsed));
nameValuePairs.add(new BasicNameValuePair("sWeatherInformation",encodedwInfo));
nameValuePairs.add(new BasicNameValuePair("season",encodedlseason));
nameValuePairs.add(new BasicNameValuePair("sDesc",""+encodedDesc));
if(share)
{
nameValuePairs.add(new BasicNameValuePair("sShareInfo","true"));
}
else
{
nameValuePairs.add(new BasicNameValuePair("sShareInfo","false"));
}
Log.e("name value pairs",""+nameValuePairs.toString());
UrlEncodedFormEntity entity_st=new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
request.setEntity(entity_st);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Responce=EntityUtils.toString(resEntity);
Log.i("responce ======",""+Responce);
}
}
catch (Exception e) {
e.printStackTrace();
String message=e.getMessage();
Log.e("meaasge with erroe",message);
}
return Responce;
}
step 1
You have specified a "UTF-8" encoding in
UrlEncodedFormEntity entity_st=new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
Try to change it to
UrlEncodedFormEntity entity_st=new UrlEncodedFormEntity(nameValuePairs);
step 2
I noticed that the strings you are adding to the request are called encodeXXXX
Does this mean that you are encoding them before adding them to the ValuePairs?
If so, stop doing this and keep them as normal strings.