Android app remain logged into website, cookies? Session? - android

I'm looking to make an android app that is basically a custom view of a text based gaming website. I know how to do HttpPosting and such, so sending login information is relatively simple. But my question is, how would I go about then navigating the site? I've never really worked with sessions and cookies on the client side. Is a cookie the right way to implement this? How do I pass the info back to the server when accessing subsequent pages?
I hope that makes sense

Generally, in Java HttpURLConnection you can set / get a cookie this way (here is the whole connection process). The code below is in my ConnectingThread's run(), from which all the connecting activity classes inherit. All share common static sCookie string which is sent with all the requests. Therefore you can maintain a common state like being logged on / off:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//set cookie. sCookie is my static cookie string
if(sCookie!=null && sCookie.length()>0){
conn.setRequestProperty("Cookie", sCookie);
}
// Send data
OutputStream os = conn.getOutputStream();
os.write(mData.getBytes());
os.flush();
os.close();
// Get the response!
int httpResponseCode = conn.getResponseCode();
if (httpResponseCode != HttpURLConnection.HTTP_OK){
throw new Exception("HTTP response code: "+httpResponseCode);
}
// Get the data and pass them to the XML parser
InputStream inputStream = conn.getInputStream();
Xml.parse(inputStream, Xml.Encoding.UTF_8, mSaxHandler);
inputStream.close();
//Get the cookie
String cookie = conn.getHeaderField("set-cookie");
if(cookie!=null && cookie.length()>0){
sCookie = cookie;
}
/* many cookies handling:
String responseHeaderName = null;
for (int i=1; (responseHeaderName = conn.getHeaderFieldKey(i))!=null; i++) {
if (responseHeaderName.equals("Set-Cookie")) {
String cookie = conn.getHeaderField(i);
}
}*/
conn.disconnect();

Related

How to Use Both HTTPS and HTTP to parse JSON data in Android?

I followed this to Parse Json In Android
I have Successfully Done it with HttpData handler..
Here I am Successfully Posting Data to server and Getting Response..
Now I want to Use this same in the Part of HTTPS..
Can Any one suggest me How to do this Without Major Changes in my code.. Because In my application I am doing this for more activities.. Please Suggest me to Use HTTPs in my code..
I will provide Additional Info... Depending Responses...
Update
In my code I have Changed HttpURLConnection to HttpsURLConnection
Please suggest me How to through this error In my code..
Update 1
I have Changed Certificate on server side.. Now its working On Https..
But Now,
I want to Use HTTP and HTTPS Both in one app Depending on Client Requirement So here now its worked with Https....
But I also need to work with Http
In my Code Can any any one suggest me...I want I should Work with Https and Http Both In one App.
to use both HTTP and HTTPS, you need to have the 2 methods (i think you already have them)
GetHTTPData(String urlString)
GetHTTPSData(String urlString)
now in HTTPDataHandler class (where you have both methods above)
you need to create a 3rd method GetDataFromUrl(), that will check URL and decide which method to use (http or https)
public String GetDataFromUrl(String url){
if(url.toLowerCase().startsWith("https")){
//HTTPS:
return GetHTTPSData(url);
}else{
//HTTP:
return GetHTTPData(url);
}
}
now in the AsyncTask class ProcessJSON
replace this line stream = hh.GetHTTPData(urlString);
with this one stream = hh.GetDataFromUrl(urlString);
if you don't want to add that 3rd method in HTTPDataHandler, just use the if-statement in ProcessJSON at doInBackground() to call either one of the 2 methods (http or https)
You can use HttpsURLConnection, replace HttpURLConnection by HttpsURLConnection .
public String GetHTTPData(String urlString){
try{
URL url = new URL(urlString);
HttpsURLConnection urlConnection =(HttpsURLConnection)url.openConnection();
// Check the connection status
if(urlConnection.getResponseCode() == 200)
{
// if response code = 200 ok
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
// Read the BufferedInputStream
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
sb.append(line);
}
stream = sb.toString();
// End reading...............
// Disconnect the HttpURLConnection
urlConnection.disconnect();
}
else
{
// Do something
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally {
}
// Return the data from specified url
return stream;
}
What I understand is in your server side, they used self signed SSL certificate. So you have to install that certificate in your android device also. Settings > Security > install form storage.But for production build you have to buy ssl certificate from CA Authorities.
Hope this will solve your problem.
Remove HttpDataHandler lines in doInBackground use HttpUrlConnection directly in doInBackground or use HttpUrlConnection in JSONparse class to post params to server follow this tutorial to post params Website

want to build lotus notes leave application for android

I want to build lotus notes leave application on android. For that purpose I need some lotus script files which will provide me data for showing in my app. But first thing what I need is to get server login
But after trying to login I am not getting proper response. I need advice how can I proceed to build the app leave application for ibm lotus notes.
protected static void tryLogin()
{ ``
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = "username="+"ABCD"+"password="+"!!!!!!!!";
try
{
url = new URL("http://10.194.5.33/dvlp/wdcidmanage.nsf/hwlsp?wsdl");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
System.out.println("response--------------------------"+response);
// You can perform UI operations here
// Toast.makeText(this,"Message from Server: \n"+ response, 0).show();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
System.out.println("error"+"----------------error is there------------");
}
}
this is my code snippet for login. in the server side what i need to do for login ?
If I understood, your need to consume a Domino WS: http://xx.xxx.x.xx/dvlp/wdcidmanage.nsf/hwlsp?wsdl
Ask the Domino administrator to add Anonymous in the ACL of the wdcidmanage.nsf
Consume the WS in androide: http://www.c-sharpcorner.com/UploadFile/88b6e5/how-to-call-web-service-in-android-using-soap/
For an overview of Domino web server authentication see this article. I wrote the article with Domino REST services in mind, but a lot of it applies to SOAP-based services too. This is because authentication is normally done in a layer that's common to REST and SOAP.
You probably want to start with basic authentication. That means sending an Authorization header with each web service request. The value of the Authorization header is just the base64 encoded user name and password as described in this Wikipedia article.
In your comment you said, "when i am trying to establish connection with it it returns me a html page." That sounds like the server is set up for session authentication. As the first article says, you can set up a web site rule to override session authentication for your web service. Then you will get back an HTTP 401 response when the request isn't properly authenticated.

Better method to store user credentials

Ok, so I am trying to develop a mobile website application for the iPhone and Android. Currently my site uses cURL to log the user into the other site. I have a PHP script that creates a cookie based on the username of the user. cURL then places the info into that cookie. The cookie is stored on my site's host.
Basically this mobile site I am creating is suppose to allow users to log into a forum that I developed this for (site owner would not allow me to create a mobile version on their site so needed to do it on mine). Then once they log in they can read posts and reply to them. When it goes to read a thread needs to load the cookie, as well as when they try to make a post.
How can I get the cookie to save to the users phone rather than my server? The reason I ask is, I'd like it so my host doesn't get filled up with dozens of text files with credentials of users (which I don't want to see so I am not phishing).
I want it so the user signs in, cookie gets saved to the phone. They want to read a post the phone pulls up that cookie. They want to post, phone pulls up the cookie.
I looked into PHP setcookie() function, wasn't sure if that is what I needed.
Any help provided will be appreciated.
When you set a cookie on the server side that cookie gets sent to the client (your phone in this case) via something called HTTP Headers. There is a HTTP Header with the name "Set-Cookie" and a Value of the cookie. When the browser makes a request to the server in the future, its expected to give that value back in a HTTP Header called "Cookie"
So, if you want to set a cookie and use that cookie its a matter of getting the cookie from your request, storing it somewhere safe, and giving it back in future requests.
http://en.wikipedia.org/wiki/HTTP_cookie
Here is a simple Authentication method that takes an url, a username and a password and returns the cookie value.
static public String authenticate(String service_url, String username, String password) throws IOException
{
if (username == null || password == null)
throw new IOException();
String charset = "UTF-8";
URL url = new URL(service_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset="+charset);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setReadTimeout(5000); // 2 second timeout.
String query = String.format("Email=%s&Password=%s",
URLEncoder.encode(username, charset),
URLEncoder.encode(password, charset));
OutputStream output = null;
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
}
connection.getInputStream();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
if (cookies == null)
throw new IOException();
for (String cookie : cookies)
{
if (cookie.startsWith("authcookie"))
return cookie; // this is the only correct path out.
}
throw new IOException();
}
Example HTTPGET, note the http header to add the cookie value back to requests.
public static InputStream getDataFromHTTP(String url, String authenticationCookie, String mimetype) throws ClientProtocolException, IOException
{
DefaultHttpClient client = getHttpClient();
if (client == null)
throw new IOException("Cant getHttpClient()");
if (url == null)
throw new IOException("URL is null");
HttpGet httpget = new HttpGet(url);
httpget.addHeader("Accept", mimetype);
httpget.addHeader("Cookie", authenticationCookie);
httpget.addHeader("Accept-Encoding", "gzip");
HttpResponse response = client.execute(httpget);
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
return instream;
}

how to find operator name from website phone no. search page in android application?

I need to find operator name from phone no. using this website in my android application.
Requesting and parsing HTML in the application works fine.
When I query request string from the app:
address: .https://nummertjanster.pts.se/net/en/Nummerkapacitet/Enskiltnummer?&_rp/pts.SearchNumber_ndc=70&_rp/pts.SearchNumber_operator=Tele2+Sverige+AB&_rp/pts.SearchNumber_telnumber=4264128
I need to specify 'operator name' ..which is wierd I guess.
The problem is no matter which number (ndc-telnumber) I enter if I specify a operator name in the request string the resulting webpage shows that operator name.
Here are some numbers to test:
073-3355433 = Telenor Sverige AB
073-6107353 = Tele 2 Sverige AB
070-3999266 = TeliaSonera Sverige AB
073-2404070 = Glocalnet AB
How can I find the proper operator name for a specific number?
Thanks for your any help.
There are a couple of issues with the site that prevent things from working:
It needs a cookie for the POST to work.
The operator name is actually not returned as part of the page, it is returned as part of a location redirect (302).
This chunk of code does what you want (I was dodging work, so I actually tidied it up for you): it hits the main page, fetches/extracts the cookie returned, posts the area code and number to the website and then intercepts the Location header and pulls out the operator name. Note that the area code is not always 3-digits (so for example for 073-3355433 you would do String operatorName = findOperator("73","3355433");.
String findOperator(String ndc, String number)
{
String parameters = "action=search&ndc="+ndc+"&number="+number+"&search=S%F6k";
HttpURLConnection httpUrlConnection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
int code = 0;
String response = null;
try {
java.net.URI u = new java.net.URI("https://nummertjanster.pts.se/net/sv/Nummerkapacitet/Enskiltnummer");
httpUrlConnection = (HttpURLConnection) u.toURL().openConnection();
httpUrlConnection.setConnectTimeout(7500);
httpUrlConnection.setReadTimeout(7500);
httpUrlConnection.setRequestMethod("GET");
httpUrlConnection.connect();
String cookie = httpUrlConnection.getHeaderField("Set-Cookie");
u = new java.net.URI("https://nummertjanster.pts.se/actionrequest/sv/Nummerkapacitet/Enskiltnummer?__ac_/pts.SearchNumber");
httpUrlConnection = (HttpURLConnection) u.toURL().openConnection();
httpUrlConnection.setConnectTimeout(7500);
httpUrlConnection.setReadTimeout(7500);
httpUrlConnection.setRequestProperty("Cookie", cookie);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
httpUrlConnection.connect();
outputStream = httpUrlConnection.getOutputStream();
outputStream.write(parameters.getBytes("UTF-8"));
httpUrlConnection.setInstanceFollowRedirects(false);
try {
inputStream = httpUrlConnection.getInputStream();
} catch (IOException e) {
//andrologger.warn("An error occurred while POSTing to " + url, e);
}
code = httpUrlConnection.getResponseCode();
response = httpUrlConnection.getHeaderField("Location");
if(response != null){
response = response.split("&")[2].split("=")[1];
}
}catch(Exception e1){
android.util.Log.v("Configuration","Exception: "+e1.getMessage(), e1);
} finally {
closeQuietly(outputStream);
closeQuietly(httpUrlConnection);
}
return response;
}
Tested it on my phone and it works fine: let me know how it works for you.
It clearly doesn't work restfully. You'll have to find another way.
Perhaps imitate the form post that the page is doing: http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
EDIT this doesn't work
Pretty simple:
https://nummertjanster.pts.se/net/sv/Nummerkapacitet/Enskiltnummer?&__rp_/pts.SearchNumber_ndc=PUT_AREA_NUMBER_HERE&__rp_/pts.SearchNumber_operator=xxno_operatorxx&__rp_/pts.SearchNumber_telnumber=PUT_NUMBER_HERE
i.e.
https://nummertjanster.pts.se/net/sv/Nummerkapacitet/Enskiltnummer?&__rp_/pts.SearchNumber_ndc=696&__rp_/pts.SearchNumber_operator=xxno_operatorxx&__rp_/pts.SearchNumber_telnumber=1788300

Android POST data and COOKIES

I have a username as password which I need to send to a website as part of an android application (yes it is https), and once submitted to the seerver via POST, the server should return cookies. I need to be able to capture these cookies, and allow them to be accessed in a webview which I have settup.
How would I do this?
Thanks
You can call the setCookie function on the CookieManager instance, which you can get by calling a static method on it named getInstance.
Generally, in Java HttpURLConnection you can set / get a cookie this way (here is the whole connection process):
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//set cookie. sCookie is my static cookie string
if(sCookie!=null && sCookie.length()>0){
conn.setRequestProperty("Cookie", sCookie);
}
// Send data
OutputStream os = conn.getOutputStream();
os.write(mData.getBytes());
os.flush();
os.close();
// Get the response!
int httpResponseCode = conn.getResponseCode();
if (httpResponseCode != HttpURLConnection.HTTP_OK){
throw new Exception("HTTP response code: "+httpResponseCode);
}
// Get the data and pass them to the XML parser
InputStream inputStream = conn.getInputStream();
Xml.parse(inputStream, Xml.Encoding.UTF_8, mSaxHandler);
inputStream.close();
//Get the cookie
String cookie = conn.getHeaderField("set-cookie");
if(cookie!=null && cookie.length()>0){
sCookie = cookie;
}
/* many cookies handling:
String responseHeaderName = null;
for (int i=1; (responseHeaderName = conn.getHeaderFieldKey(i))!=null; i++) {
if (responseHeaderName.equals("Set-Cookie")) {
String cookie = conn.getHeaderField(i);
}
}*/
conn.disconnect();

Categories

Resources