Android post variables to drupal - java

Hi I'm writing an app for both iOS and Android to interface with a druapl site. I'm trying to allow users to login to the website and then save the data from successful logins in the preferences of the app. Below I was able to successfully do what I wanted in Cocoa but I have been unable to get it to work in Java. Both code snippets are below. Any help with the java would be greatly appreciated.
I'm just not getting any response at all from the java the response comes back as an empty string when it should be a long JSON response.
Cocoa Login (Working)
NSURL *url = [NSURL URLWithString:#"http://examplesite/api/rest/user/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSData *requestBody = [[NSString stringWithFormat:#"username=%#&password=%#",[userField text],[passField text]] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestBody];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
Java Login (Not Working)
class loginTask extends AsyncTask<Void, Void, Void> {
HttpResponse response;
public loginTask() {
}
#Override
protected Void doInBackground(Void... arg0) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://examplesite/api/rest/user/login");
try {
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "password"));
post.setEntity(new UrlEncodedFormEntity (formparams));
response = client.execute(post);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
//TODO finish the activity
try {
Toast.makeText(Login.this, EntityUtils.toString(response.getEntity(), "UTF-8"), Toast.LENGTH_SHORT).show();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

There's things for this like. Drupal iOS sdk and dandy for android

Looking at the examples you've listed you aren't submitting the same payload on iOS and Android.
On iOS you are correctly POSTing form data with username=foo&password=bar, but on android you are asking for the string representation of your JSONObject which is { 'username': 'foo', 'password':'bar' }.
Rather than using a JSONObject you should checkout URLEncodedUtils, in particular the format method.

Related

Android - Display data from MySQL

I'm very new to Android and I'm currently making an application wherein the user can enter and ID number once (that serves as a login) and he can use access the rest of the features of the app.
I'm currently stuck in the displaying of a data from the MySQL server. Using the ID that the user entered (which is unique and only the user's identificaton), I can display the information with of the user (through TextView or something).
This is my code so far:
public class MainActivity3Activity extends Activity {
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
TextView tv;
TextView tv2;
String get;
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
tv = (TextView)findViewById(R.id.tv);
tv2 = (TextView)findViewById(R.id.tv2);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://usamobileapp.pe.hu/webservice/student_info.php");
SharedPreferences preferences = getSharedPreferences("rfid", Context.MODE_PRIVATE);
if(preferences.contains("rfid")){
get = preferences.getString("rfid", null);
}
}
So my question what do I do from here? I'm quite familiar about httpost but I'm wondering how do I display the user information using the previously entered ID during the login? I heard things like JSON parsing but I'm not quite sure on how to use it.
How do I get to display the information of the user matching the ID he entered? How to diplay using a TextView?
Thanks for the help.
PS. Please disregard the webview there. I only used it as a sample if my app really us connected to my php.
1) make a restful API on your server
2) receive API elements on your client (android), i suggest retrofit, its too easy
3) display your data! otto will help :)
want more? more ,
it might seem hard, but if you study for a few days you'll learn it.
To implement a login / registration system using MySql you need a server-side API, for example in PHP to manipulate the database.
You need something like that on the server side:
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
And the function that queries the database:
public function getUserByEmailAndPassword($username, $password) {
$query = $this->dbh->prepare("SELECT * FROM users2 WHERE username = :username");
$query->bindParam(':username', $username);
$result = $query->execute();
// check for results
if ($query->rowCount() > 0) {
$result = $query->fetch(PDO::FETCH_ASSOC);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return false;
}
}
The android 'calls' the php scripts:
private static String login_tag = "login";
public void loginUser(String username, String password) throws ExecutionException, InterruptedException {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
jsonParser = new DbHandler(activity, this, params).execute();
}
And here is the DbHandler:
public DbHandler1(Activity activity, MyCallback dbIntf, List<NameValuePair> params) {
this.activity = activity;
intf = dbIntf;
this.params = params;
}
public JSONObject makeHttpRequest() {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(MainActivity.baseUrl);
//If database contains greek characters instantiate with UTF-8 Encoding
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (HttpHostConnectException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, R.string.connection_error, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
try {
//If database contains greek characters instantiate with UTF-8 Encoding
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
#Override
protected JSONObject doInBackground(Void... params) {
jObj = makeHttpRequest();
return jObj;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
try {
intf.onRemoteCallComplete(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
So the php scripts 'catches' the tag and if the user exists it returns a JSON response to the device. For example:
{
"tag": "login",
"success": 1,
"error": 0,
}
The data transfered from the MySql server must be JSON encoded.
On the android device you must read the JSON Response and act accordingly.
Take a look here for more details.
login / registration system
json parsing
you need perform network operations on a separate thread from the UI.
reade aboute rest Google I/O 2010 - Developing Android REST client application
documentation
in the client, for rest api i like use retrofit + gsongroundy
or php, very easy create rest api using slim framework ─ How to create REST API for Android app using PHP, Slim and MySQL

Android httpclient login to Rails server

I started to learn about how to make an Android application. I tried to connect my app to rails server by using httpclient, however I cannot understand how to connect between app and the remote server.
Here is part of my code, and I matched id form inside "BasicNameValuePair" with html id values. Please let me know how to check whether login is successful or not.
class SendPost extends AsyncTask<Void, Void, String>
{
protected String doInBackground(Void... unused) {
String content = executeClient();
return content;
}
protected void onPostExecute(String result) {
}
public String executeClient() {
ArrayList<NameValuePair> post = new ArrayList<NameValuePair>();
post.add(new BasicNameValuePair("user_name", "SallyCook"));
post.add(new BasicNameValuePair("user_email", "domain#ppls.kr"));
post.add(new BasicNameValuePair("user_password", "add123456"));
post.add(new BasicNameValuePair("user_password_confirmation", "add123456"));
post.add(new BasicNameValuePair("user_phone", "01013089579"));
HttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
System.out.println(params);
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
HttpPost httpPost = new HttpPost("http://www.ppls.kr/users/sign_up");
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(post, "UTF-8");
httpPost.setEntity(entity);
HttpResponse responsePost = client.execute(httpPost);
System.out.println(responsePost.getStatusLine());
HttpEntity resEntity=responsePost.getEntity();
if (resEntity != null) {
Log.w("RESPONSE", EntityUtils.toString(resEntity));
}
return EntityUtils.getContentCharSet(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

Fill form from Java Android and send Request

I'm trying to fill form from Java program for Android and send request to the server. First I tried to use a Selenium for Android, but I failed to start it, then I found to many examples about, how to use HttpPost etc.., but the action of the form is:
form name="mainform" method="POST" action="/system/boxuser_edit.lua"
So I found the following code, and I tried to many possible combination, but without success
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),100000);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 100000);
String SID = "xxxxxxxxx";
HttpPost httpPost = new HttpPost("http://fritz.box/system/boxuser_edit.lua?sid="+SID+"=new");
BasicNameValuePair emailBasicNameValuePair = new BasicNameValuePair("user", paramUsername);
BasicNameValuePair passwordBasicNameValuePair = new BasicNameValuePair("password", paramPassword);
// We add the content that we want to pass with the POST request to as name-value pairs
//Now we put those sending details to an ArrayList with type safe of NameValuePair
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePair);
try {
// UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs.
//This is typically useful while sending an HTTP POST request.
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
// setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
httpPost.setEntity(urlEncodedFormEntity);
try {
// HttpResponse is an interface just like HttpPost.
//Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the JAVA API, InputStream constructor do nothing.
//So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(givenUsername, givenPassword);
}
i have just bunch of questions before we discuss your code because what you did here seems to be correct.
First of all did you request a permission to access network in the manifest file?
if it's not this is how you do it:
add this line of code to your androidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
But before that you have to check that the link you are passing to the HttpPost Object is working, you can use a web browser to test it, because i just did that right now and it seems that it doesn't work!!

Android application database connectivity with web app using Jsp

I am developing a web app in JSP. For same project I'm developing an Android app. The web app uses Apache Tomcat and MySQL. Now I want to log in from the Android application by retrieving data from MySQL database. But how?
I did find many tutorials but all are using PHP scripts. I'm using Eclipse for both apps.
For android Try this.
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
And then
public static String sendFirst(String requestString) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(universal_URL_MENU+"?request_menu="+start_menu);
HttpResponse response = client.execute(request);
System.out.println("response in class"+response);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
// }
}catch(Exception e){
e.printStackTrace();
System.out.println("catch");
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
Where
public static String universal_URL_MENU = "http://192.***.1.#:9999/my_Project/ReqFromTabFor.do";
Now for Jsp or Servlet
try{
PrintWriter out=res.getWriter();
String subcategory=req.getParameter("request_menu");
System.out.println("Receive : "+subcategory);
JSONObject jobj=UserDelegate.reqFromTabForMenuBySCatg(subcategory);
}
if(jobj!=null){
out.println(jobj);
}else{
out.print("Sorry Not Available");
}
}catch(Exception e){ e.printStackTrace(); }
What happens between the client (your Android app) and the server is loosely coupled, meaning that they are not related whatsoever except for the protocol with which they communicate, which for a web service is HTTP.
Usually a client (either an app or a web browser) makes an HTTP request sending parameters (e.g. login, password) with POST or GET methods. The server takes these parameters and processes them according to its needs.
This may sound obvious, but you say that all the tutorials are using php script, so you seem confused: your problem on Android? or is your problem in the server?
The code you need in your Android app is EXACTLY THE SAME regardless of the server technology (asp, cgi, jsp, php...) and database (MySql, Oracle...), because the HTTP protocol is standard.
Here is an example I copied from here to make a simple HTTP request with two POST parameters.
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", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
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
}
}

Make JSON Request from android

I have got the following objective-c code which does what I need to do for android but have no idea how to go about it. I need to access a php file on a webserver which will return a JSON string (Dictionary I think?). Below is the code I have for the iPhone version:
+ (NSDictionary *)getNewMission:(int)maxID
{
NSString *serverUrl = #"http://www.website.com/api/api.php";
NSString *methodString = [NSString stringWithFormat:#"\"method\":\"getNewItem\",\"max_item_id\":\"%d\"", maxID];
NSString *postStr = [NSString stringWithFormat:#"json={%#,\"key1\":\"%#\",\"key2\":\"%#\"}", methodString, KEY_1, KEY_2];
return [JsonManager handleJSONRequest:postStr baseURL:serverUrl];
}
+ (NSDictionary *)handleJSONRequest: (NSString*)postString baseURL:(NSString*)baseUrl
{
NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:baseUrl]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSDictionary *results = [data JSONValue];
[data release];
return results;
}
Where should I be looking to help with replicating this in android? I really don't have any meaningful JSON experience especially not in Java/Android. Any help is appreciated.
Here is the code for the Android activity to read from the Web Service and parse the JSON object:
public void clickbutton(View v) {
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("user", "1");
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8080/sample1/" +
"webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("idusers", jObject.getString("idusers"));
map.put("UserName", jObject.getString("UserName"));
map.put("FullName", jObject.getString("FullName"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
For more details see http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php

Categories