want to build lotus notes leave application for android - 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.

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

Android & C# Web API - Using Google OAuth2 to log-in to Web API from Android app

Background:
I've got a C# website that requires OAuth Google log-in to access it's pages.
I also have an Android App where I want to access this Web API's pages (with HttpGet-requests and use the returned JSON). I did indeed make an OAuth Google log-in in my Android App, but I need to somehow use that to log-in on the Web API.
I used to have a POST on my C# website that required an AntiForgeryToken to log-in. Because these AntiForgeryTokens only exists very very short (Session-based and changes whenever another page is opened, even the same page in the same browser), I was forced to find a different way. (Because I tried to send a HttpPost in my Android App to log-in with an AntiForgeryToken that I received as a response in the last HttpGet-request, but this token just keeps changing non-stop and caused a no-match in my HttpPost response..)
Current:
Instead I made a new POST-method in my C# web project that doesn't require this [ValidateAntiForgeryToken]. I've also made a System.Web.Security.Role for the Web API pages, and in my API Controllers I've added [Authorize(Role = "web_api")].
When I tested this on my browser:
I removed all Cookies I have in my FireFox browser
I start a Private (Incognito) Window
And used the plug-in RESTClient to make the following POST:
URL: http://localhost:54408/Account/ApiLogin
Headers: Content-Type: application/x-www-form-urlencoded
Body: provider=Google&returnUrl=/Cart/Bestellen
It works with the following response:
When I try to go to this same POST on my Android app however (using the AsyncTask POST-method at the bottom of this page), I get an Error 400 (OAuth2 Error)!!1 in my response.
So, my question: How could I use this new POST that doesn't require any AntiForgeryToken to log-in with an OAuth Google Log-in on my Android App.
Or should I use a completely different approach to log-in with an OAuth Google account on my C# Web API, from within my Android app? (Could I send the OAuth user data from the separate Google log-in in the Android app itself through a different POST? Can I produce this GoogleAccountsLocal_session cookie that is somehow created after the POST-request myself in my Android App to use and put in the HttpClient? So I can get the same response as with the RESTClient POST-request above; if this is indeed the needed cookie to make it work?)
TL;DR: How to log-in to an OAuth2 Google secured C# Web API from within an Android App (so I can send the Web API HttpGet-requests and get JSON returned), without using AntiForgeryTokens whatsoever?
Thanks in advance for the responses.
Android POST class:
public class TaskPostAPI extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls){
String response = "";
for(String url : urls){
InputStream content = null;
BufferedReader buffer = null;
try{
// Get the baseUrl from the given url
URL u = new URL(url);
String baseUrl = u.getProtocol() + "://" + u.getHost();
HttpPost post = new HttpPost(url);
// Add the default Content-type to the Header
post.addHeader("Content-type", "application/x-www-form-urlencoded");
// POST-request requires provider and returnUrl
List<NameValuePair> nvPairs = new ArrayList<NameValuePair>(2);
nvPairs.add(new BasicNameValuePair("provider", "Google"));
nvPairs.add(new BasicNameValuePair("returnUrl", baseUrl));
post.setEntity(new UrlEncodedFormEntity(nvPairs));
// Send the POST-request
HttpResponse execute = MainActivity.HttpClient.execute(post);
// Get the response of the POST-request
content = execute.getEntity().getContent();
buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while((s = buffer.readLine()) != null)
response += s;
}
catch(Exception ex){
ex.printStackTrace();
}
finally{
try{
if(content != null)
content.close();
if(buffer != null)
buffer.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}
}
return response;
}
}

Prestashop and web service(Restful), HttpURLConnection, BufferedReader

I want to access the resources of a site created by prestashop via restful web services, which I enter the URL you must enter a key (that is generated by prestashop when we create a restful web service) in the field of username.
so I am trying to read a xml string:
<?xml version="1.0" encoding="UTF-8"?>
<prestashop>
<manufacturers>
<manufacturer id="1" xlink:href="http://127.0.0.1/test/api/manufacturers/1" />
<manufacturer id="2" xlink:href="http://127.0.0.1/test/api/manufacturers/2" />
</manufacturers>
</prestashop>
over HTTP:
I have the following code:
public class MainTest
{
public static String readUrl(HttpURLConnection conn) throws Exception
{
BufferedReader reader = null;
try
{
reader = new BufferedReader(new InputStreamReader((conn.getInputStream())));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally
{
if (reader != null)
reader.close();
}
}
public static void main(String[] args) throws Exception
{
URL url = new URL("http://127.0.0.1/test/api/manufacturers");
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(30000);
conn.setRequestProperty("Accept", "application/XML");
conn.setRequestProperty("Authentication-Key", "ALHKUNM0J6JJAQC21E4TVWHBM6FAKACF");
System.out.println("true2");
String xml="";
xml = readUrl(conn);
System.out.println(xml);
}
}
but it give me this error
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 401 for URL: http://127.0.0.1/test/api/manufacturers
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.test.services.URLReader.main(URLReader.java:28)
i think the problem is in this ligne
reader = new BufferedReader(new InputStreamReader((conn.getInputStream())));
please help me if you have any solution
regards
You request property for authentication is wrong!
First, Prestashop REST API is using basic authentication.
Then you will need to encrypt your credentials based on base64 encryption.
So download commons-codec-1.5.jar from http://commons.apache.org/proper/commons-codec/.
Here is the way I did it.
import org.apache.commons.codec.binary.Base64
//.....
String username = "Your Prestashop webservice key";
String password = "";// leave it empty
String authToBytes = username + ":" + password;
//....
byte authBytes = Base64.encodeBase64(authToBytes.getBytes())// I keep it generic
String authBytesString = new String(authBytes);
//then your code
conn.setRequestProperty("Authorization", "Basic " + authBytesString);
//...
It should work now.
Find a small Prestashop java API at http://www.onasus.com/2012/10/3712/prestashop-web-services-java-api/
I found many many other ways to consume the web services. One of them uses the class java.net.Authenticator which handles the HTTP Basic authentication for you automatically. Find out more at http://examples.javacodegeeks.com/core-java/net/authenticator/access-password-protected-url-with-authenticator/ .
From HTTP Status Codes:
401 Unauthorized
Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided.[2] The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource. See Basic access authentication and Digest access authentication.
Try to find out what kind of authentication your service demands. Often it's easier to play around with curl before you write a program with HttpURLConnection.
curl -v \
-G \
-H 'Accept: application/xml' \
-H 'WWW-Authenticate: Basic 938akjsdfh==' \
http://127.0.0.1/test/api/manufacturers
Another thing: you should always check the response code before accessing getInputStream(). If you encounter something like 4xx, getInputStream() will throw an exception. In this case, maybe you can grab some information of the error if you read from getErrorStream().

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;
}

Android app remain logged into website, cookies? Session?

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();

Categories

Resources