I'm a junior developer who has been working on a RSS Reader.
I'm trying to download a webpage from my app for offline viewing but I am having a few issues.
When I try to download an asp page I don't seem to get the right content, but instead a html page with asp form widgets.
Can anyone help me with understanding what's going on and how I could possibly download the content of the page?
I should also mention the webpage is a sharepoint webpage using https ssl authentication, using httpclient as my means to connect and download the webpage.
To communicate with ASP you usually need to send __VIEWSTATE and _EVENTVALIDATION tokens in your HttpPost and other requests. You can get those once by calling HttpGet on the basic page and using Patten with regexes or a simple str.contains("_VIEWSTATE") and strip it out of the HTML and send with every request.
If you're not doing any POSTs, just basic GETs, then make sure you're setting the headers appropriately, as so:
HttpGet req = new HttpGet("YOUR SITE'S URL");
req.setHeader("Content-Type", "application/x-www-form-urlencoded");
req.setHeader("Host", "YOUR SITE'S ROOT PAGE");
req.setHeader("User-Agent", "Mozilla/5.0 ...");
req.setHeader("Accept-Encoding", "gzip,deflate,sdch");
req.setHeader("Accept", "text/html,application/xhtml+xml,application/xml");
req.setHeader("Accept-Language", "en-us,en");
req.setHeader("Accept-Charset", "ISO-8859-1,utf-8");
HttpResponse resp = client.execute(req, localContext);
Don't forget about the possible session cookie you can store in httpcontext and also pass in with every execute as seen above:
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
The best way to go about it in theory is to download Fiddler, run the site in Chrome, see what's going on and emulate actual browser requests in your app: http://www.fiddler2.com/fiddler2/
Related
I know there are plenty of resources like this on the web, and the closest I've come was the answer to this question: ASP.NET Web API Authentication.
Basically, this is my requirement. Log in via android to my account on an MVC4 internet application I created (which uses SimpleMembership). It is NOT an MVC Web Api app, which seems to confuse things when looking at the various ways of achieving this.
I am attempting to use FormsAuthentication to set an authentication cookie, but I have no idea how to configure my android httpclient to actually send through this authentication cookie, or how to get MVC to save a session from my android app.
So far, this is what I've come up with on the MVC side:
[HttpPost]
[AllowAnonymous]
public bool LoginMobi(LoginModel model)
{
var membership = (SimpleMembershipProvider)Membership.Provider;
if (membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return true;
}
else return false;
}
And I use the following java in my android app (sent over an SSL connection):
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://mysite/api/login");
List<NameValuePair> nameValue = new ArrayList<NameValuePair>();
nameValue.add(new BasicNameValuePair("UserName", "foo"));
nameValue.add(new BasicNameValuePair("Password", "bar"));
httppost.setEntity(new UrlEncodedFormEntity(nameValue));
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
// etc etc
What I haven't figured out is how to receive the authentication cookie on android and send it back with each request to controllers with the [Authorize] attribute. I'm rather new to this so please forgive my ignorance!
You are using FormsAuthentication which uses cookie to identify user for each request. You have two options here.
Use CookieStore for HttpClient. Check Android HttpClient and Cookies
OR
Combine BASIC auth and FormsAuthentication. Check Combining Forms Authentication and Basic Authentication
Hope this helps.
I am working on an app which shall log in to a web site (via http://......?password=xyz).
I use DefaultHttpClient for this.
Along with the GET response, the website sends a cookie, which I want to store for further POST requests.
My problem is that client.getCookieStore().getCookies() always receives an empty list of cookies.
If I open http://www.google.com (insted of my intended website), I receive the cookies properly, but the website I am working with, seems to send the cookie in some other way (it's a MailMan mailing list moderating page)
I can see the respective cookie in Firefox cookie manager, but not in Firebug network/cookie panel (why?). InternetExplorer HttpWatchProfessional however shows the cookie when recording the traffic....
There is some small difference, I observed between the cookies www.google.com sent and my target website: In HttpWatchProfessional, those cookies from google are marked as "Direction: sent", while the cookie from my website are marked as "Direction: Received".
(how can the google cookies be sent, while I cleared browser/cookie cache just before?)
Can someone explain the difference to me?
My code is the following:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse execute = client.execute(httpGet);
List<Cookie> cookies = client.getCookieStore().getCookies();
After further investigation, I found out that the cookie was received, but actually rejected by the httpclient, due to a path the cookie, which differed to that from the called URL.
I found the solution at:
https://stackoverflow.com/a/8280340/1083345
I'm writing an Android app that should get data from a certain web application. That web app is based on Servlets and JSP, and it's not mine; it's a public library's service. What is the most elegant way of getting this data?
I tried writing my own Servlet to handle requests and responses, but I can't get it to work. Servlet forwarding cannot be done, due to different contexts, and redirection doesn't work either, since it's a POST method... I mean, sure, I can write my own form that access the library's servlet easily enough, but the result is a jsp page.. Can I turn that page into a string or something? Somehow I don't think I can.. I'm stuck.
Can I do this in some other way? With php or whatever? Or maybe get that jsp page on my web server, and then somehow extract data from it (with jQuery maybe?) and send it to Android? I really don't want to display that jsp page in a browser to my users, I would like to take that data and create my own objects with it..
Just send a HTTP request programmatically. You can use Android's builtin HttpClient API for this. Or, a bit more low level, the Java's java.net.URLConnection (see also Using java.net.URLConnection to fire and handle HTTP requests). Both are capable of sending GET/POST requests and retrieving the response back as an InputStream, byte[] or String.
At most simplest, you can perform a GET as follows:
InputStream responseBody = new URL("http://example.com").openStream();
// ...
A POST is easier to be performed with HttpClient:
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("name1", "value1"));
params.add(new BasicNameValuePair("name2", "value2"));
HttpPost post = new HttpPost("http://example.com");
post.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
InputStream responseBody = response.getEntity().getContent();
// ...
If you need to parse the response as HTML (I'd however wonder if that "public library service" (is it really public?) doesn't really offer XML or JSON services which are way much easier to parse), Jsoup may be a life saver as to traversing and manipulating HTML the jQuery way. It also supports sending POST requests by the way, only not as fine grained as with HttpClient.
I have an android app that is working fine when connected to a production web server. A development server was created for testing future releases. It's an IIS server that's locked down with username/password.
I am trying to use httpclient.getCredentialsProvider() to send a username and password so I can authenticate to the page before doing anything else but it doesn't seem to be working correctly so I assume I am missing some code or doing something wrong.
I tried messing with the credentials and sending the port and full url but that didn't work either so I just switched it to null and -1 which from what I gather means it should work on any site any port, but every way I tried still got the same result of not authenticating.
Here is what I have now.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);
httpclient.getCredentialsProvider().setCredentials(new AuthScope(null,-1), new UsernamePasswordCredentials("someusername", "somepassword"));
HttpPost httpost = new HttpPost("someURL");
Other non-relevant code to set Name Value Pair for posting
Then
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
httpost.setEntity(formEntity);
HttpResponse response = httpclient.execute(httpost);
IIS supports HTTP authentication methods like Basic, Digest and Integrated. The problem is that all of them are hardwired to Windows accounts. This means that you need a Windows user on your server for every account you want to HTTP-auth enable.
Having the ability to do plain Basic Authentication agains account stored e.g. in a database would be very handy for a range of situations like web applications, (WCF) web services, REST services, Silverlight service backends etc.
enter link description here
I need to create an Android application, I'm not sure which is a better way of doing this by better I mean should I use the WebView or create an application .
I need to implement the existing application which is a ASP.NET application which mainly consists of a login screen, once the user logs in he will see a list a items in probably a gridview based on the selection from the gridview. He then will be shown more detailed info about the selected item.
The above is a web application I need to implement this as a app on Android phone.
Also there will be a need to use the GPS where based on the GPS values the department will be selected and also use the camera to take a picture and save it on to the server .
A solution which I was thinking of was to expose .NET web services and then access it in the android phone!
But I am very new to Android development and really do not how to go about this. Is there any better solution?
Can anyone help me as to how do I go about this ?
Pros:
Android App may work faster then web applications (but still depends on web page complexity)
By the help of this community and android developer site you can complete your app within a 2-3 weeks.
As you stated picture capture/upload and GPS etc are advantages of the smart phone app.
Cons:
Later, you may need iPhone, Blackberry apps!
Instead of .Net web service which typically returns XML, you can go for HTTP call with JSON response (I've seen it in Asp.net MVC). So that you can easily parse the data on android app.
Added:
HTTP call:
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(getString(R.string.WebServiceURL) + "/cfc/iphonewebservice.cfc?returnformat=json&method=validateUserLogin&username=" + URLEncoder.encode(sUserName) + "&password=" + URLEncoder.encode(sPassword,"UTF-8"));
HttpResponse response = httpClient.execute(httpGet, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
JSONObject JResponse = new JSONObject(sResponse);
String sMessage = JResponse.getString("MESSAGE");
int success = JResponse.getInt("SUCCESS")
There are two approaches available to you:
Build an Android app.
Build a webapp, using W3C geolocation to access GPS coordinates. (see geo-location-javascript)
If you go for option (1), you'll want to expose your .NET service as a simple REST API (using JSON as Vikas suggested to make it just that bit simpler!)
Android already comes with all the components needed to access and parse such a REST API, specifically the Apache HTTP and JSON packages, and can be iterated on rather quickly once you have the basic request/parse framework in place.