Stay logged in on a website in an application lifecycle - android

I was able log in through my android app to http://yearbook08.com/ using this code:
String URL="http://yearbook08.com/login.php";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userId", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now when I move to another activity I want to retrieve http://yearbook08.com/wall.php but the web server does not recognize my last login and asks me to login again.
Is there a way that I can stay logged in after once logging in? Kindly help !

Your code does not take into account session management. This happening as after a successful login no cookies are set, so if you send another request the initial authentication is lost and server takes it to be a fresh request.
I would suggest you use Apache httpcomponents library 4.x (httpclient in particular)
Create a httpcontext and attach a cookie store as
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet("http://www.google.com/");
// Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget, localContext);
Make use the same localContext in the subsequent requests. Also note cookiestore and httpcontext should be declared as static or global variables as their scope must exist wherever you carry the httprequest. You don't have to set cookies on your own, it is automatically done!
And do read about HttpComponents 4.x http://hc.apache.org/httpcomponents-client-ga/index.html
Update 1:
Make sure it is v4 and v3. basicCookiestore has only been present since v4. It is clear now that you are using v3 which does not know about basiccookiestore object. Add the v4 library to your project. It will solve your problem
Update 2
If you try to retrieve http://yearbook08.com/wall.php from the 2nd activity this problem will arise as the 2nd activity won't have httpcontext,httpclient or the Cookiestore object in it. So it will send a fresh request.
1st approach
So you should try to fetch the contents you need in the first activity itself and then pass on the fetched data to the 2nd activity. This way you'll have session maintained.
2nd soln
If you are not satisfied with this you can check this out http://www.jameselsey.co.uk/blogs/techblog/android-implementing-global-state-share-data-between-activities-and-across-your-application/ Share httpcontext, cookiestore and httpclient across the activities to accomplish the task.

Related

Stream Data to Website from Android device

For a project I would like to stream the sensor data of an Accelerometer (from an android phone) to a website.
Basically I have written the application that reads the data and stores it on the phone and converts it to a string. I just want to plot the x, y and z Values as line graph dynamically on a website. So If I shake my phone, the line on the website should be moving.
I had several ideas like using Node.js or Java webserver but I couldn't found any appropriate tutorials.
So maybe someone got a good idea where to find tutorials, where I can learn how to stream data to a website from my phone. It should be easy to do or not that hard but I am not very good in making webservers or so.
Keep sending your data to the server ideally making post request.
Your webserver can just read the data from the obtained requests and update the graph.
How to write a server ? go through the below link
http://tutorials.jenkov.com/java-multithreaded-servers/singlethreaded-server.html
how to post data from android ? use an async task doing the below things
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.server.com/");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("graphvalue", "12345"));
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
}
}

Is there any way to create a mini-proxy for http on android?

I am working on a HttpClient that posts something to a website. The client looks something like this (based on this link):
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
}
}
What I want to do now is to create a small proxy service (a VERY simple one) that runs on the same android device and listens for the outgoing HTTP connexions and modifies the POST ( for example change the "id": "12345" into "54321", just for testing purposes), and then pass the HttpRequest to the actual website. How cand I do something like that? I've been googling around but found nothing that could give me an idea how to do it(like a tutorial or something). Can anybody give me an idea of how to do that?
You do not need to write code to achieve this. Instead of writing your own proxy and since you only need it to test you application, you can use the mitmproxy which is a man-in-the-middle proxy (based on your description that is what you want to achieve). Follow this tutorial to set up your PC as the proxy and the device as your client.
http://blog.philippheckel.com/2013/07/01/how-to-use-mitmproxy-to-read-and-modify-https-traffic-of-your-phone/

Android : Post data to a website via app and view results in app

I have an application which converts a website to mobile format. There is a spinner in the app. So my doubt is, how do i pass these selected values from my spinner to the website to get results?
You need to make a http post request.
http://developer.android.com/reference/org/apache/http/client/HttpClient.html.
NOTE : If you are making network related operation you should use a AsyncTask other wise you will get a NetworkOnMainThreadException (Honeycomb and later).
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
}
}
Some links with source code available in the links below
http://www.androidhive.info/2011/10/android-making-http-requests/
http://android-er.blogspot.in/2011/09/example-of-httppost-on-android.html
Since you are running the a mobile web application inside a WebView container you can use a well known library like jQuery an its ajax stuff.

Android to Drupal user creation

For anyone who might need help creating a Drupal user from an Android app, the following code works:
//create a new HttpClient and post header
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://test.site.com/testpoint/user/register");
// TODO Auto-generated method stub
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add( new BasicNameValuePair("account[pass]", "cutelady"));
nameValuePairs.add( new BasicNameValuePair("account[mail]", "scarter#sgc.gov"));
nameValuePairs.add( new BasicNameValuePair("account[name]", "Samantha Carter"));
httpPost.setEntity( new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
}catch(Exception e){
Log.e("HTTP ERROR", e.toString());
}
However, I have an additional problem: when using the profile module to provide additional custom CCK fields for the user registration process, I can't find the right account[cck_parameter] to connect and save my Android data to the profile CCK field.
What can I try to resolve this?
User is a user object and extra profile values are node objects. So the user_save function is designed to accept few params.
The key is, you can create user profiles overriding "required field" status of the user/register form.
Keep the current form, and try to create a new node too, after saving the user object.
See content profile API to see how to save(it's a node_save() ) a content profile.

HttpServletRequest get no parameters from my httppost

I have just a curiosity question. I have an HttpPost request in Android that looks something like this:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(getString(R.string.url));
//This code does not work
HttpParams params = new BasicHttpParams();
params.setParameter("type", "20");
post.setParams(params);
try {
HttpResponse response = client.execute(post);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
On my server side, I have a servlet that listens for requests and parses the parameters:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Enumeration en = request.getParameterNames();
while (en.hasMoreElements()){
System.out.println(en.nextElement());
}
}
When I execute this code, the servlet does not see any parameters at all. But if I replace the whole "parameter" chunk with this code:
//This code works
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("type", "20"));
try {
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
My servlet can parse parameters. It's not a problem, I'm just going to use the entity but my question is, why can't my servlet getthe parameters from the first code chunk? What's wrong with setParams? Why can the servlet see parameters if I make them an entity?
In HTML when we have something like "http://host/path?user=uname&passwd=pass", we call the part (user=uname&passwd=pass) after the question mark "form data".The "form data" can be attached to the end of the URL after a question mark (as above), for GET requests, or sent to the server on a separate line, for POST requests.The "form data" are split to parameters. The parameters are separated by & when we use GET.
In our case the HttpPost and HttpGet classes extend the AbstractHttpMessage which implements the setParams method. This method is same for GET and POST but does the job only for GET! In the case of GET the parameters are put in the URL. In the case of POST you need to set the entity for the parameters to be on a "separate line".
On the server side when using servlets the getParameters is clever enough to find the parameters for GET and POST.
Thats why on the server side we do not need to change the code for getting the parameters!
Hope I helped!

Categories

Resources