Android:How to retrieve data from phpliteadmin to android application..? - android

I have connected database with phpliteadmin using xampp on localhost. Now I have to retrieve data from localhost and also to update it.. So any 1 can help me out from this problem..??

ok i have a function that sends some data to your local host and retrieve some data from there
use this method for communication :-
public void postData() throws Exception {
postData=et.getText().toString(); //some value
HttpClient httpclient = new DefaultHttpClient(); // connection
HttpPost httppost = new HttpPost("http://192.168.1.21/default.php"); //ip of your local host and php file!
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("msg", ""+str));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
ResponseHandler<String> responseHandler=new BasicResponseHandler(); // to get the response printed there
String responseBody = httpclient.execute(httppost, responseHandler); // here we are recieving values.
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
and you can use this php coding to send and retrieve values :-
<?php
include ('MCrypt.php'); //this my encryption example
$thename=$_POST["msg"]; //get values from there using post and "msg" must be same on both side!
$mcrypt = new MCrypt();
$decrypted = $mcrypt->decrypt($thename);
echo("Your Encrypted String:--".$thename."\n"); // this line will be sent to android and will be recived in String Response;
echo("Your Decrypted String:--".$decrypted);
?>

Related

How to send an http request to custom api using Oauth 2.0 with AsynceTask

I would like to send an http request to custom api.
I have the request details, and it is working using postman(http client).
Im trying to translate that request to android, using AsyncTask.
I couldnt managed to understand few things:
first, how to send the Bearer token that I have(oauth 2.0).
the second, how to send a jason body.
all the details about the request are in the following link:
https://web.postman.co/collections/7428863-ca5b907d-2752-4d4e-b8a8-29d5cd0dc098?version=latest&workspace=03f5fe5b-0ecd-43f8-8759-3aa868f4cb7f
my "DoInBackground" :
protected Void doInBackground(Void... voids) {
response = null;
Log.v("DoInBackground","entered");
//sending Data
if (valid) {
Log.v("ifvaild","entered");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzcsu4e68qfgi56y7l2qu5ky40da2o.ui.nabu.casa/api/services/script/turn_on");
//httpPost.addHeader("Accept-Language", "he");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer My Bearer"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("script.turn_on", "script.gt1"));
Log.v("nameValue","entered");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
try {
response = httpClient.execute(httpPost);
Log.v("HttpClient","entered");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
this is not working, I get an authentication failure from the server
thanks for your help!
You need to add those pairs in the header. And add the body as entity.
// headers
httpPost.addHeader("Authorization", "Bearer My Bearer");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("script.turn_on", "script.gt1");
// body
String bodyString = "{\"data\":1}"; // your json string
StringEntity bodyEntity = new StringEntity(bodyString);
httpPost.setEntity(bodyEntity);
Just a tip. Look into Retrofit2 library to do all of this.

Android posting data to server using HTTPPOST after encoding using BASE64

I am trying to send data to server using HTTPPOST. I have encoded username and password using BASE64.encodetoString(). But I am unable to post the data. There is no error but I am getting 400 or 404 response code every time. The code is successfully executed when done in Java, but it is not working as expected in android. Please help me.
Here is the code I am using:
public void getLoginInfo()
{
String user="xxxx#gmail.com";
String password="1234xyz";
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(url);
// String base64EncodedCredentials = "Basic " + Base64.encodeToString((user + ":" + password).getBytes(),0);
// Building post parameters
// key and value pair
byte[] data=(user+":"+password).getBytes();
String base64EncodedCredentials =Base64.encodeToString(data, Base64.DEFAULT);
String httpheader="Basic "+base64EncodedCredentials;
System.out.println("httpheader "+httpheader);
/* List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("email", "nishanth.s#giwitservices.com"));
nameValuePair.add(new BasicNameValuePair("password","100006438166763hbsV1v0"));*/
// Url Encoding the POST parameters
// Making HTTP Request
// try {
try {
httpPost.setHeader("Authorization", httpheader);
//httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
System.out.println("response test "+response.toString());
System.out.println("response code "+response.getStatusLine().getStatusCode());
String the_string_response = convertResponseToString(response);
System.out.println("respones "+the_string_response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Instead of using BASE64.DEFAULT, try to use BASE64.NO_WRAP. That would help you in resolving the issue.
Change this:
String base64EncodedCredentials =Base64.encodeToString(data, Base64.DEFAULT);
To this:
String base64EncodedCredentials =Base64.encodeToString(data, Base64.NO_WRAP|Base64.URL_SAFE);
Hope this helps.
Why don't you use this :
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("key_of_data", data));
HttpPost oHttpPost = new HttpPost(your_url);
oHttpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Instead of using Base64 encoding

HTTP Post OK, how to display the response?

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());

Web Service using HTTP Protocol in Android

can anyone give me an idea of using web service using HTTP protocol.
Here is an example for "Executing a HTTP POST Request with HttpClient":
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("username", "Paresh"));
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
}
}
We can use web services in our application to send and receive data from a remote server. Consider the case of an login section from a application where you need to pass username and password to the server for checking the whether the user is a valid user or not. In this case the username and password are attached with a url and send it to the remote server for validation and in response you get a value stating whether the user is a valid user or not. Usually the response will be either in XML format or JSON format from there we need to parse that response to get the necessary values. Check out the following example code in this I have created a class named "parsing" and it using the http protocol to receive a data.
public class parsing extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://services.digg.com/topics?appkey=http://example.com&type=json";
HttpPost post = new HttpPost(postURL);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
String response=EntityUtils.toString(resEntity);
response=response.trim();
Log.i("RESPONSE=",response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
See the response on the Logcat and do not for get to include <uses-permission android:name="android.permission.INTERNET" />
because we are fetching the data from the remote server which needs internet permission.

403 FORBIDDEN message when I use HttpPost to send data to Django

I am trying to send data from android to Django app. I want to store the data in a table in sqlite database called "mytable". Here is the android code:
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", "david");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nameValuePairs.add(new BasicNameValuePair("year", j.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// myTextView.setText(j.toString());
HttpResponse response = httpclient.execute(httppost);
myTextView.setText(response.getStatusLine().toString());
// myTextView.setText(response.toString());
}catch(Exception e) {
myTextView.setText("Error in http connection "+e.toString());
}
The issue is resolved now. I only needed to have a return value
Sounds like Django's Cross-Site Request Forgery framework, which by default prevents third-party POST requests. Read Django's CSRF docs for details.

Categories

Resources