Best way to store & use cookies android with HTTPPost & HTTPClient? - android

I'm coding a login system which will keep the user permanently logged on (until username or password is incorrect) but I'm having an issue with cookie storage. What I want to do is have the cookies store in local storage (probably shared preference). Though I have no idea where to start. This is my main HTTP Post function.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add your data
httppost.setHeader("X-Requested-With", "XMLHttpRequest");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
StringBuffer sb = new StringBuffer();
BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
return sb.toString();
} catch (Exception e) {
//TODO: WIP
e.printStackTrace();
}
I want to set the cookies first (of course if there are any) then I would like to resave them after the httppost has executed. Where can I go about doing this?
Edit there is about 4 cookies that are saved.

This should help you get started:
http://docs.oracle.com/javase/tutorial/networking/cookies/definition.html
Check out this post as well:
https://stackoverflow.com/a/3587332/2495131

Related

Android CouchDB {"error":"bad_request","reason":"invalid_json"}

While trying to Create a new Document in my IrisCouch Database, i am always getting following error:
{"error":"bad_request","reason":"invalid_json"}
This is the relevant part of my function:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://username.iriscouch.com:6984/mydb");
StringEntity entity = new StringEntity(body);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.toString()) ;
HttpEntity httpEntity = httpResponse.getEntity();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
System.out.println("body: " + body);
} catch (Exception e) {
e.printStackTrace();
}
Here is my System.out of "body":
{"bild1":"","bild2":"","bild3":"","bild4":"","bild5":"","bild6":"","bild7":"","bild8":"","bild9":"","bild10":"","name":"","plz":0,"ort":"","strasse":"","n_koordinate":0,"e_koordinate":0,"beschreibung":"","groesse":"< 50m²","sitzplaetze":"< 50","grillstellen":"1","reservierung":false,"res_name":"","res_tele":"","res_weiteres":"","wc":true,"behindi":false,"dach":true,"kinderfreundl":false,"auto":false,"kinderwagen":false,"einkauf":false,"datum":"2015-07-01-14:12:01:856","bewertung":0,"anz_bewertung":0}
The JSON is valid. Tested it with jsonlint.com JSON Validator.
What could i do? Thanks in advance!
Perhaps the unicode superscript 2 (²) is bothering it?
Not sure which library this HttpPost is, but seems a lot like the HttpWebRequest, so try setting your header this way:
httpPost.setHeader("Content-type", "application/json charset=utf-8");
It could also be that the HttpPost class doesn't properly encode strings.
(I haven't pasted this in my Visual studio, so just a shot in the dark)

Passing cookie with an HTTT GET

I am trying to get a list of user subreddits via the reddit api. Currently I am able to do a post for login which returns a cookie and modhash. Those are the parameters I'm passing to my method below. However each time I call the function I get an empty response:
"{}"
How can I pass a cookie and modhash via HTTPGET to get a valid response?
public void getUserSubreddits(String[] loginInfo){
HttpClient client = new DefaultHttpClient();
URL url = null;
try {
url = new URL("http://www.reddit.com/subreddits/mine/.json?limit=100");
HttpGet httpGet = new HttpGet(String.valueOf(url));
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
httpGet.addHeader("cookie", loginInfo[1]);
httpGet.addHeader("modhash", loginInfo[0]);
HttpResponse response = client.execute(httpGet);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
Log.d(TAG,total.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
It was a simple mistake. To anyone in the future trying this I solved the problem by using Chrome to inspect the headers of an active session on http://www.reddit.com/subreddits/mine/.json?limit=100 url and found that the cookie header started with:
reddit_session
So I removed the modhash changed the my header parameter to read:
httpGet.addHeader("cookie", "reddit_session="+loginInfo[1]+";");
With this I got a valid response.

Android - Cookies in HttpContext is not retrieving more than once for each URL

I'm trying to retrieve JSon information for a server that is protected and is redirected to the login page everytime that is trying to get a protected resource. So I should use cookies to implement the access to the information.
Unfortunately POST for each URL(in total 3)that I have, is just working once.
To log in the app is made using the function below:
// Making HTTP request
try {
httpClient = getNewHttpClient();
String redirectedUrl = getUrl(url);
// defaultHttpClient
HttpPost httpPost = new HttpPost(redirectedUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", login));
nameValuePairs.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpContext = new BasicHttpContext();
CookieStore mCookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore);
HttpResponse response = httpClient.execute(httpPost, httpContext);
HttpEntity entity = response.getEntity();
String html = null;
if (entity != null) {
InputStream instream = entity.getContent();
try {
html = streamToString(instream);
} finally {
instream.close();
}
}
if ((html != null) && html.contains("error loginError")) {
} else
return html;
} catch (IOException e) {
}
And after the log in I'm trying to get the information in the same way, but it's just working once per URL. I don't know why, below is how I'm trying to get the information after login.
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost, httpContext);
HttpEntity entity = response.getEntity();
String html = null;
if (entity != null) {
InputStream instream = entity.getContent();
try {
html = streamToString(instream);
} finally {
instream.close();
}
}
When I'm trying to get the information second time the IOException is throwed, the httpClient and httpContext are both global and static.
I got a solution, I don't think that is a good solution, but it is working at all.
To make it stops to get the IOException, I just made a call to the login function before all post, which means that for all POSTs I have to set a new HTTPContext logged and valid.
If somebody has a better solution I would be pleasure to hear it from you.
PS.: Actually the problem was about the session duration on server side, now it's working properly, anyway I'll let the topic here because could be useful to somebody that is implementing this kind of solution.

Android Json Get URL STOPPED

I just started the topic to get data from a JSON OpenData and visualize via my phone.
I followed this tutorial and it has worked all :)
https://www.learn2crack.com/2013/10/android-asynctask-json-parsing-example.html
The url whew i get the datas is :
http:// + api.learn2crack.com/android/json/ (sorry for that, I don't have a good reputation :) )
Then I wanted to try a Opendata me and my android application stops, the url is:
http://ckan.opendata.nets.upf.edu/storage/f/2013-11-30T16%3A49%3A59.118Z/london.json
You can see it's the same and I only change the name of URL in the code.
You know if the problem is because of the OpenData? and I need some permission? Because when I execute the second part my app stopped
Here, this will work. I am using Strict Policy but normally you should use Async. Please google this as to why we should use Async instead of Strict Policy. This is irrelevant here
When i am using HttpPost to get your json from url, i am getting these errors :-
405 Method Not Allowed
The method POST is not allowed for this resource.
You cannot POST a file
so i am using HttpGet :-
String url = "http://ckan.opendata.nets.upf.edu/storage/f/2013-11-30T16:49:59.118Z/london.json";
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
JSONObject jObj = new JSONObject(sb.toString());
JSONArray json2 = json.getJSONArray("user");
for (int i = 0; i < json2.length(); i++) {
JSONObject c = json2.getJSONObject(i);
}
}
catch (Exception e) {
e.printStackTrace();
}

Interpreting HTTP POST response

I'm trying to use HTTP POST to submit user information on a University login page. To do so I run the postData() method below. The code posts the credentials and reads the response. Below the code I have shown what the response status line and response entity show. (I edited the username and password for security ;) ).
It appears to execute since I get a response from the website, but I don't know how to interpret what it says or what I need to do to have a successful login. The website in question has a username field (id = user), password field (id = pass), and login button (id = submit). It is a secure website (https), but for now I'm not doing a SSL connection as I'm just trying to get this code working.
The immediate questions I have are: is it possible I need the SSL connection to make it work, and is Java an issue as mentioned in the response?
A little more background... This is done in a service, and it's the only task. If Java is the issue, how would I enable it without a webview?
public void postData() {
// Create a new HttpClient and Post Header
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost("https://wiscmail.wisc.edu/login/");
TextView info = (TextView) findViewById(R.id.info);
EditText user = (EditText) findViewById(R.id.user);
EditText pass = (EditText) findViewById(R.id.pass);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", user.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("pass", pass.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Log.v(TAG, response.getStatusLine().toString());
info.setText(response.getStatusLine().toString());
HttpEntity responseEntity = response.getEntity();
Log.v(TAG, responseEntity.toString());
String response_string = inputStreamToString(response.getEntity().getContent()).toString();
Log.v(TAG, response_string);
} catch (ClientProtocolException e) {
Log.v(TAG, "client protocol exception");
info.setText("client protocol exception");
} catch (IOException e) {
Log.v(TAG, "IO exception");
info.setText("IO exception");
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
response.getStatusLine
HTTP/1.1 200 OK
response.getEntity().getContent()
<html><head></head><body onLoad="document.relay.submit()">
<form method=post action="https://login.wisc.edu/?appurl=wiscmail.wisc.edu/login"
name=relay><input type=hidden name=pubcookie_g_req
value="b25lPXdpc2NtYWlsLndpc2MuZWR1JnR3bz1XaXNjTWFpbCtMb2dpbiZ0aHJlZT0xJmZvdXI9YTUmZml2ZT1QT1NUJnNpeD13aXNjbWFpbC53aXNjLmVkdSZzZXZlbj1MMnh2WjJsdUx3PT0mZWlnaHQ9Jmhvc3RuYW1lPXdpc2NtYWlsLndpc2MuZWR1Jm5pbmU9MSZmaWxlPSZyZWZlcmVyPShudWxsKSZzZXNzX3JlPTAmcHJlX3Nlc3NfdG9rPTM5NjgzODc5MSZmbGFnPTA=">
<input type=hidden name=post_stuff value="user=username&pass=password">
<input type=hidden name=relay_url value="https://wiscmail.wisc.edu/PubCookie.reply">
<noscript><p align=center>You do not have Javascript turned on, please click the
button to continue.<p align=center><input type=submit name=go value=Continue>
</noscript></form></html>
EDIT:
Per suggestion I tried adding a setHeader to the http client, but I got the same response form the website.
httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
httppost.setHeader("Accept", "application/x-www-form-urlencoded");

Categories

Resources