Android: Example for using a cookie from HttpPost for HttpGet - android

I am able to use the example here: http://www.androidsnippets.org/snippets/36/index.html and successfully get the "HTTP/1.1 OK" response for a webesite I am sending the HttpPost along with the user credentials. However, I am unable to use an HttpGet to further browse other pages on this site.
Can anyone please let me know, what's going wrong. I am sorry - I am very new to Java.

My guess would be that when the website gets the Post and logs the user in, it sets cookies on the response to indicate that the user is logged in, and then requires those cookies on subsequent Get's.
You will need to do something like the following (this is borrowed from a bigger app so may not compile right out of the box)
DefaultHttpClient mHttpClient = new DefaultHttpClient();
BasicHttpContext mHttpContext = new BasicHttpContext();
CookieStore mCookieStore = new BasicCookieStore();
mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore);
This sets up a cookie store within the HTTP context, and you then use that context on Get's and Post's. For example...
HttpResponse response = mHttpClient.execute(mRequest, mHttpContext);
Under the covers the HTTP client will store cookies from responses, and add them to requests.

Related

HTTP Request header issue in Android

I am trying to fire an API in which I need to add two headers i.e token and deviceid. Below is my code to add header:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(nameValuePairs[0].get(0).getValue().toString());
nameValuePairs[0].remove(0);
ResponseHandler<String> res = new BasicResponseHandler();
// set header
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setHeader("deviceid", "358978060711939");
httpPost.setHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJHVUlEIjoiYjdlNjZiOWQtMjBjNy00MGI2LTliMzgtOTc3OGQ2OWIwM2E1IiwiRU5USVRZIjoiRUFCTSIsIlVOSVQiOiJVQk0yIiwiUk9MRU5BTUUiOiJTRUxGIiwiSUQiOiIwMDAyMzciLCJBTFRJRCI6IjMzMyIsIlVTRVJfTkFNRSI6IkFuaWwiLCJMT0dJTl9HVUlEX0tFWSI6ImU2NWM2YWEzLTZlNDItNDUyYS1hOGEwLWRlYzRhMGRiNTIxNyIsImlhdCI6MTQ1OTI0ODkyM30.m742d9xd6XlBBjZ3_ODWuoCEdWvSkhPAuNrDee1vi74");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs[0]));
response = httpClient.execute(httpPost, res);
In Response I am getting: org.apache.http.client.HttpResponseException: Not Found
When I replace token with any alpha numeric value then I am getting response with error message. But when I passed actual token value which is mentioned above I am getting exception. Even I tried with addHeader function also but getting same issue. I am unable to understand how to resolve this error.
it's the handler which is causing the error. Don't use.
You should either write your own handler or call execute without a handler.
httpClient.execute(httpPost);//remove the handler
I hope this is helpful. ThankYou
Your token seems to be incorrect. Header set in HTTP protocols has their own restrictions. To check it, just try to send your trim token (ex 30 chars).
If it don't helped, you have incorrect another parameters. Anyway, i would give you advice, to use Retrofit.

Servlet sessions in an android app

I'm currently making an android app that makes POST requests to a tomcat server which makes a session for the user, though the sessions seem to not be working. I'm getting a new session with each request. Is there any way to keep this session or track the user another way? The code for querying the server is generally as follows:
HttpClient client = new DefaultHttpClient();
HttpPost post = HttpPostFactory.getHttpPost("AuthenticateUser");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("option1", option1);
pairs.add(new BasicNameValuePair("option2", option2);
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
StringBuilder builder = new StringBuilder();
Scanner in = new Scanner(response.getEntity().getContent());
while (in.hasNext()) {
builder.append(in.nextLine());
}
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(MyStringUtil.toInputStream(builder.toString()));
I have full source code access to both the client and server, so a solution on either end will work.
You keep recreating your HttpClient; unless you have your own cookie store implementation that will keep cookies across instantiations or otherwise restores them, they'll keep going away.
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html
I believe tomcat uses a JSESSIONID to maintain sessions. This is stored as a cookie. In order to keep that same session alive, you'll need to send the cookies along with your next HttpRequest.

Can I send a Android HttpGet (not HttpPost) with 1 string param?

Im coding a RESTful API & Android client at the same time as I go and im currently working on pulling the users profile from the server. I feel like this should definitely be a get request being that im only pulling existing data and im not adding/editing anything to my database, but I do need a user_id param to be able to query for the appropriate profile. Can I send just one tiny little variable along with my HttpGet some how or am i supposed to use a HttpPost in this situation regardless?
Android uses Apache's HTTPClient. So, copying their tutorial code:
public void sendStringTo(String remoteUrl, String myString) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(remoteUrl+"?string1="+myString);
HttpResponse response1 = httpclient.execute(httpGet);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST either fully consume the response content or abort request
// execution by calling HttpGet#releaseConnection().
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
httpGet.releaseConnection();
}
return;
}
GET can support adding variables/parameters. For example you could make a Url that looks like this:
http://yourwebsite.com/script.php?user_id=19898424

HttpPost: No "Set-Cookie" Header

I want to get the session cookie of a website. Unfortunately the "Set-Cookie"-Header doesn't show up.
Here's the code I've written:
"commands" is a String[][] and the whole code is wrapped by try/catch.
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE,cookieStore);
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>(0);
for (int i=0;i<commands.length;++i)
nvps.add(new BasicNameValuePair(commands[i][0],commands[i][1]));
httppost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
Header[] headers = response.getAllHeaders();
List<Cookie> cookies = cookieStore.getCookies();
String data = EntityUtils.toString(entity);
My understanding of Http Communication tells me that there should be a "Set-Cookie" Header. The only Headers I get from response.getAllHeaders() are Connection:close, X-Powered-By:PHP/4.3.4 and Content-Type:text/html
There is a bit of javascript included in the returned data (response.getEntity()).
<script language = "javascript">
<!--
location.href="/index.php";
function SetCookie(name,value,expire,path){
document.cookie = name + "=" + escape(value) + ((path == null) ? "":(";path="+path))
}
var iad = 461180104
SetCookie("iad",iad,0,"/")
-->
</script>
As far as I understand this, this code is never executed because it's just a comment ?!
But as well this is probably the bit where the cookie should be created.
Any ideas?
UPDATE:
"Opera Mobile" is the only browser for Android I found which has no problem with cookies on this site. "Opera Mini", "Dolphin HD" and the Froyo Stock browser all fail. No Desktop browser has problems connecting. Is this a webkit issue? And if this is the case: how to avoid it?
Using Chrome's developer tools or Firebug, check the HTTP response for the "expires" parameter in the Set-Cookie header field. Make sure the time / date settings on the phone are set correctly. If the browser thinks the cookie is already expired, it won't store it.
If that doesn't work try using wireshark / tshark to grab a trace of the communication from your client, and compare it to a browser that's working the way you expect it to.
By the way, the comment delimiters around that bit of Javascript don't prevent the script from being run; they just prevent older (really old) browsers from trying to render the script in the document. That cookie ("iab") doesn't look like the cookie for authentication. There's likely an http-only cookie with a session identifier; you should be able to see it using the aforementioned Firebug / Dev tools.

Android HTTP login questions

I am implementing a login feature in Android.
Does android have anything like sessions or cookies? How should I 'remember' that the user is loged in? Obviously I don't want to ask for the password every time my application is used!
Should I hash the password before sending it to the server? I have a table in my database with a user and password column. When I want to check the login, should I send the password hashed to the server like login.php?u=sled&p=34819d7beeabb9260a5c854bc85b3e44, or just plain text like login.php?u=sled&p=mypassword and hash it on the server before I perform the authentication?
Does android have anything like sessions or cookies?
Yes. There are two alternatives.
Option #1:
You can use CookieManager to set your cookie.
Option #2:
The other alternative (I'm using this alternative in one of my applications) is to grab your cookie after you've sent your username and password to the server (e.g. via HttpPost or HttpGet). In your question you're using $_GET style of your login authentication, so my sample code will be using HttpGet.
Sample code using HttpGet:
HttpParams httpParams = new BasicHttpParams();
// It's always good to set how long they should try to connect. In this
// this example, five seconds.
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
DefaultHttpClient postClient = new DefaultHttpClient(httpParams);
// Your url using $_GET style.
final String url = "www.yourwebsite.com/login.php?u=myusername&p=mypassword";
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
try {
// Execute your HttpGet against the server and catch the response to our
// HttpResponse.
response = postClient.execute(httpGet);
// Check if everything went well.
if(response.getStatusLine().getStatusCode() == 200) {
// If so, grab the entity.
HttpEntity entity = response.getEntity();
// If entity isn't null, grab the CookieStore from the response.
if (entity != null) {
CookieStore cookies = postClient.getCookieStore();
// Do some more stuff, this should probably be a method where you're
// returning the CookieStore.
}
}
} catch (Exception e) {
}
Now when you have your CookieStore; grab a list of cookies from it and after that you can use Cookie to determine the name, domain, value etc...
Next time you're trying to access "locked" content of your website; set a cookie to your HttpURLConnection from your Cookie information:
URL url = new URL("www.yourwebsite.com/lockedcontent.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setInstanceFollowRedirects(false);
// "Host" and "Cookie" are fields in the HTTP response. Use WireShark
// via your computer to determine correct header names.
httpURLConnection.setRequestProperty("Host", domainOfYourCookie);
httpURLConnection.setRequestProperty("Cookie", valueOfYourCookie);
final int responseCode = httpURLConnection.getResponseCode();
// And get the content...
Should I hash the password before sending it to the server?
Depends on how your system is designed. You must have correct information when sending it to your server. This also depends on how you're hashing your information in your .php file.
How should I 'remember' that the user is loged in?
Store the information in a SharedPreferences or something. Like I said earlier, you can hash it if your login system is correctly designed - this depends on how you're hashing it in your .php file.

Categories

Resources