I am interfacing my Android app with my Drupal website. In my app I am creating user accounts to that website using the standard PHP user_save. What I need to move my app from the current activity to the next is a value to be returned form that PHP form which is creating my Drupal user account.
SO when an account is created, a value of 'invalid' or 'valid' would be returned from the php form like so:
// User Authentication
$responsep="valid";
$responsen="invalid";
if(!user_authenticate($username, $password)){
drupal_json_output($responsen);
}else{
// Logs the USER in
$account = user_authenticate($username, $password);
$user = user_load($account, TRUE);
drupal_session_regenerate();
drupal_json_output($responsep);
}
Question is, how do I, in my android java method, retrieve that returned value of either valid or invalid so that I may use it to make other decisions such as try agin or change activities?
I have updated the code above
Here is the part from my App which is sending the user data:
public void createUserAccount(String usernameFinal, String passwordFinal,
String userEmail) throws ClientProtocolException, IOException {
// POST Username data to php
String uri = "https://url/hstusercreate.php";
Log.d("Action", "Posting user data to php");
HttpClient client = new DefaultHttpClient();
HttpPost getMethod = new HttpPost(uri);
Log.d("Posting Location", uri);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Log.d("Posting Username", usernameFinal);
nameValuePairs.add(new BasicNameValuePair("username", usernameFinal));
Log.d("Posting Pass", passwordFinal);
nameValuePairs.add(new BasicNameValuePair("password", passwordFinal));
//Log.d("Posting Email", userEmail);
//nameValuePairs.add(new BasicNameValuePair("email", userEmail));
getMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
client.execute(getMethod);
Log.d("Action", "Finished Posting Data to PHP");
// Return the message from php
// If Successful then stop the creation of another user
}
The easiest thing to do would be to return either JSON or XML from your PHP which your app can then read and parse.
Actually you could even just print "valid" or "invalid" on the page, and then use something like JSoup in your app to read the webpage and extract the string.
Related
I have to read contents of a certain field from a webpage. I have been told that I need to get the whole page and then extract the text from the html content.
I am using the following program to get the required page html content.
Now the issue is that this webpage takes a few seconds to load the actual text value that I want to read even though the rest of the static page components are loaded earlier. And my program kind of returns the html content after the static components are loaded but before my value is loaded. So, the final HTML that I get has the page loading process pic instead of the actual value.
Could anyone please guide me on the required changes in this program that would help it wait until the page is completely loaded?
HttpPost post = new HttpPost("https://..../login");
//prepare get method
HttpGet httpget = new HttpGet("https://...../value#/123");
// add parameters to the post method
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", "<name>"));
parameters.add(new BasicNameValuePair("password", "<password>"));
try {
UrlEncodedFormEntity sendEntity = new UrlEncodedFormEntity(parameters, HTTP.DEF_CONTENT_CHARSET);
post.setEntity(sendEntity);
// create the client and execute the post method
HttpClient client = HttpClientBuilder.create().build();
HttpResponse postResponse = client.execute(post);
System.out.println("Statusline: " + postResponse.getStatusLine());
//Output the Response from the POST
System.out.println(getStringFromInputStream(postResponse.getEntity().getContent()));
//releasing POST
EntityUtils.consume(postResponse.getEntity());
//Execute get
HttpContext context = new BasicHttpContext();
HttpResponse getResponse = client.execute(httpget);//, context);
System.out.println("Statusline: " + getResponse.getStatusLine());
if (getResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
throw new IOException(getResponse.getStatusLine().toString());
System.out.print(getStringFromInputStream(getResponse.getEntity().getContent()));
you can also use Jsoup library
visit http://jsoup.org
I have to pass UserName and password as arguments into GET method for validation.after processing I need to get response.so how can I pass value into RESTful webservice GET method?
To pass parameters in HTTP GET you should use a ? delimiter. Such as
https://mywebsite.com/user/login?username=bob&password=123
https://mywebsite.com/user/login?paramname1=value1¶mname2=value2
Make sure to always use https with any sensitive data. You may also need to escape/encode both username and password to allow extended ASCII. If you need to support UNICODE you should consider using a POST request.
I think, you should use POST method if you want to do something with user name and password. because when you use GET method, the password would be visible on the URI,
https://samplesite.com/page/login?username=John&password=123
https://sampleste.com/page/login?name1=value1&name2=value2
Instead, you could use POST method to send user name and password values and in that case the URI would like below
https://samplesite.com/page/login
And the values will be sent as,
POST /page/login.asp HTTP/1.1
Host: samplesite.com
name1=value1&name2=value2
And you get below advantages on POST Method for secured transaction with server.
It never cached
Requests will remain in the browser history
Requests cannot be bookmarked
Requests have no restrictions on data length
You can do the following for Login validation,
// Create a new HttpClient and Post Header
String downloadedString= null;
HttpClient httpclient = new DefaultHttpClient();
//for registerhttps://te
HttpPost httppost = new HttpPost("YOUR LOGIN URL");
//add data
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", UserName_Edit.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", userPassword_Edit.getText().toString()));
//add data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream in = response.getEntity().getContent();
StringBuilder stringbuilder = new StringBuilder();
BufferedReader bfrd = new BufferedReader(new InputStreamReader(in),1024);
String line;
while((line = bfrd.readLine()) != null)
stringbuilder.append(line);
downloadedString = stringbuilder.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("downloadedString:in login:::"+downloadedString);
Use AsyncTask for your authentication and write the above method in the doInBackground().
EDIT
You can follow below tutorials also,
http://sarangasl.blogspot.in/2011/06/android-login-screen-using-httpclient.html
http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
Hope it helps.
Hi you can pass arguments to GET method in RESTfull like :
http://yoururl/<arg1>/<arg2>
eg.
http://yoururl/abc/123
Just to make things clear, I have virtually no experience in HTTP. This project is very ambitious for me, but I am willing to learn in order to be able to accomplish it. I have done some searching for examples across the net, but I can't seem to find an adequate solution. I am aware of terms like GET and POST and understand the basic way to programmatically interact with a website.
Basically, the company I'm working with has a website with a database of clients that I can login to. For starters, I just want to be able to write an Android app that is able to login to the main page with my Username and Password. The site has a login URL of https://"app.companysite.com"/Security/Login.aspx?ReturnUrl=%2fHome%2fDefault.aspx and has a certificate that is for the following purpose: "Ensures the identity of a remote computer".
Is what I'm doing possible? Eventually I would like to be able to open up a Client page and edit their data and re-submit it, but one step a time.
It would be awesome if you could either point me in the direction of some relevant reading material or source code that could help me accomplish my goal.
Thanks in advance!
I don't know if this helps, but the way I did my logins is just for justification. So What I did (since I am assuming the verification is done through a MySQL database) is to create a php file that just verifies the login username and passwords are correct and print out a "correct" or "Yes" otherwise just a "No" or "invalid". Something like this :
php
//Connects to your Database
$username = $_POST['username'];
$password = $_POST['password'];
//make your mysql query if the username and password are in the database
//if there is a an approval
$approval = 1
//otherwise
$approval = 0
if ($approval > 0) {
echo "correct";
} else {
echo "invalid";
}
?>
Now in Android you could make this request to call this website and return the output like the following :
HttpParams httpParameters = new BasicHttpParams();
//make a timeout for the connections in milliseconds so 4000 = 4 seconds httpParameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
int timeoutConnection = 4000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 4000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("your website URL");
// Add your data
String username = "your username";
String password = "your password";
List<NameValuePair> nameValuePairs;
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String lines = "";
String data = null;
ArrayList<String> al = new ArrayList<String>();
while((lines = in.readLine()) != null){
data = lines.toString();
al.add(data);
}
in.close();
//To get the response
if(al.get(0).equals("correct")){
//Your login was successful
}
else {
//Your login was unsuccessful
}
I hope this helped you a bit and pointed you in the right direction.
Here is Java code that POSTs data to a website and than gets redirected as a response (status 302). It works perfectly on my PC (Eclipse, Java, Ubuntu), it does exactly what I want it to do.
I tried quite everything to post the code functionality but I just am not able to.
Java code:
// Preparing the CLIENT and POST Method
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://na.leagueoflegends.com/ladders/solo-5x5");
try {
// Add your POST METHOD attributes
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("op", "Search"));
nameValuePairs.add(new BasicNameValuePair("player", "Jaiybe"));
nameValuePairs.add(new BasicNameValuePair("ladder_id", "3"));
nameValuePairs.add(new BasicNameValuePair("form_build_id",
"form-526370b788622996caa3669e7b975ccf"));
nameValuePairs.add(new BasicNameValuePair("form_id",
"ladders_filter_form"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// RESPONE THAT WORKS WITH JAVA
System.out.println("Location:");
String LocationHeader = response.getFirstHeader("location").getValue();
System.out.println(LocationHeader);
System.out.println();
// To get the BODY I would have to parse that again - since its not REDIRECTING automatically
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost(LocationHeader);
response = httpclient2.execute(httppost2);
System.out.println("And EVEN the response body:");
System.out.println(EntityUtils.toString(response.getEntity()));
Code does:
Posts
Gets Redirected - gets header of Location
Parses the Location
And I need android to do the same. Either "Location" or body of repsonse, is ok, I dont need both.
The post: http://www.anddev.org/networking-database-problems-f29/httppost-clientprotocolexception-t56118.html
I have found the problem!
httpclient.getParams().setParameter("http.protocol.version",
HttpVersion.HTTP_1_0);
Just changing this one line - version 1_0 works and 1_1 does not. Don't ask me why :)
Thank you all!
Please try the following code. The location in the header is missing, because the page has already redirected. So we can disable redirection to get the location tag.
httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
Try calling this after you create your http client so that it follows your redirect
httpclient.getParams().setParameter("http.protocol.allow-circular-redirects", true);
I'm writing an app to check for the bus timetable's. Therefor I need to post some data to a html page, submit it, and parse the resulting page with htmlparser.
Though it may be asked a lot, can some one help me identify if
1) this page does support post/get (I think it does)
2) which fields I need to use?
3) How to make the actual request?
this is my code so far:
String url = "http://busspur02.aseag.de/bs.exe?Cmd=RV&Karten=true&DatumT=30&DatumM=4&DatumJ=2010&ZeitH=&ZeitM=&Suchen=%28S%29uchen>0=&HT0=>1=&HT1=";
String charset = "CP1252";
System.out.println("startFrom: "+start_from);
System.out.println("goTo: "+destination);
//String tag.v
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("HTO", start_from));
params.add(new BasicNameValuePair("HT1", destination));
params.add(new BasicNameValuePair("GTO", "Aachen"));
params.add(new BasicNameValuePair("GT1", "Aachen"));
params.add(new BasicNameValuePair("DatumT", day));
params.add(new BasicNameValuePair("DatumM", month));
params.add(new BasicNameValuePair("DatumJ", year));
params.add(new BasicNameValuePair("ZeitH", hour));
params.add(new BasicNameValuePair("ZeitM", min));
UrlEncodedFormEntity query = new UrlEncodedFormEntity(params, charset);
HttpPost post = new HttpPost(url);
post.setEntity(query);
InputStream response = new DefaultHttpClient().execute(post).getEntity().getContent();
// Now do your thing with the facebook response.
String source = readText(response,"CP1252");
Log.d(TAG_AVV,response.toString());
System.out.println("STREAM "+source);
EDIT:
This is my new code:
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://busspur02.aseag.de/bs.exe?SID=5FC39&ScreenX=1440&ScreenY=900&CMD=CR&Karten=true&DatumT="+day+"&DatumM="+month+"&DatumJ="+year+"&ZeitH="+hour+"&ZeitM="+min+"&Intervall=60&Suchen=(S)uchen>0=Aachen&T0=H&HT0="+start_from+">1=Aachen&T0=H&HT1="+destination+"";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
e.printStackTrace();
}
But the output file is cut-off. If I do the same request in a browser I get like 14 different routes. Now the file suddenly stops and I only get 3 routes.... what's wrong?
I solved the last problem with the cut-off string:
click here to see my solution
String url = "http://busspur02.aseag.de/bs.exe?Cmd=RV&Karten=true&DatumT=30&DatumM=4&DatumJ=2010&ZeitH=&ZeitM=&Suchen=%28S%29uchen>0=&HT0=>1=&HT1=";
That form submits by GET. You should also submit by GET. You also need to gather as many input fields (<input>, <select>, <textarea>, <button>, etc, also those of type="hidden"!) from the HTML source and specify them as parameters of your request as well. A common thing which is been overlooked in that kind of automated form submits is the name/value pair of the submit button.
This one:
<input TYPE="Submit" accesskey="s" class="SuchenBtn" name="Suchen" tabindex="20" VALUE="(S)uchen">
You need to add at least Suchen=(S)uchen to your query string. That's the only way for the server side to find out if any submit button was pressed and if so, which one, so that it can take action accordingly.
Guten Tag!
In the following extract:
<td class="Start3">
<input type="text" name="GT0" value="" tabindex="1" />
</td
The "class=start3" is instructing the browser to format a table antry in a particular way.
What you are interested in is the ">0=your text snippet on the "GET" url generated from this form.