java - Login with HTTPS to htaccess protected directory -
the app building needs perform login username , password. using defaulthttpclient execute request , setting username , password credentials. server expects htacces-login. result not logintoken hoped for. instead returns errormessage. can tell me went wrong in code? thank help! pr
private string httploginrequest() { string logintoken = null; string loginurl = "https://somedomain.com/login"; defaulthttpclient client = new defaulthttpclient(); client.getcredentialsprovider().setcredentials(new authscope(authscope.any_host, authscope.any_port), new usernamepasswordcredentials("username", "password")); httpresponse httpresponse; httpentity entity; try{ httpresponse = client.execute(request); entity = httpresponse.getentity(); if (entity != null) { inputstream instream = entity.getcontent(); logintoken = convertinputstreamtostring(instream); } } catch (clientprotocolexception e) { client.getconnectionmanager().shutdown(); e.printstacktrace(); } catch (ioexception e) { client.getconnectionmanager().shutdown(); e.printstacktrace(); } return logintoken; }
thank guys help. figured out. mix of different things: 1. cant see in code above (because removed accident) request post. our api expects request though told otherwise 2. put credentials in wrong place. have set in httpget-object in exampe given commonsware 3. have encode credentials base64 mentioned you
here code worked me:
public string httploginrequest() { string logintoken = null; string loginurl = "https://somedomain.com/login"; // defaulthttpclient client = new defaulthttpclient(); httpresponse httpresponse; httpentity entity; httpget request = new httpget(loginurl); request.addheader("authorization", "basic " + base64.encodecredentials("username", "password")); try{ httpresponse = client.execute(request); entity = httpresponse.getentity(); if (entity != null) { inputstream instream = entity.getcontent(); logintoken = convertinputstreamtostring(instream); log.d(log_tag, "login token: " + logintoken); } } catch (clientprotocolexception e) { client.getconnectionmanager().shutdown(); e.printstacktrace(); } catch (ioexception e) { client.getconnectionmanager().shutdown(); e.printstacktrace(); } return logintoken; }
when find time try example given in answer looks lot more need other requests in project.
as far know need rewrite hostnameverifier return true:
public class myhostnameverifier implements hostnameverifier { @override public boolean verify(string hostname, sslsession session) { return true; } }
i use httpsurlconnection method. therefore need create own base64 class authentication encryption , own trust manager
//kobjects // // copyright (c) 2001 stefan haustein, oberhausen (rhld.), germany // // contributors: // // license: lgpl // // library free software; can redistribute and/or // modify under terms of gnu lesser general public license // published free software foundation; either version 2.1 of // license, or (at option) later version. // // library distributed in hope useful, // without warranty; without implied warranty of // merchantability or fitness particular purpose. see gnu // lesser general public license more details. // // should have received copy of gnu lesser general public // license along library; if not, write free software // foundation, inc., 59 temple place, suite 330, boston, ma 02111-1307 // usa import java.io.*; /* * can use javax.mail.internet.mimeutility * , sun.misc.base64encoder.encode. * there non-public class in java 1.4+ called java.util.prefs.base64 */ public class mybase64 { static final char[] chartab = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/".tochararray (); public static string encode (byte [] data) { return encode (data, 0, data.length, null).tostring (); } /** encodes part of given byte array denoted start , len base64 format. encoded data appended given stringbuffer. if no stringbuffer given, new 1 created automatically. stringbuffer return value of method. */ public static stringbuffer encode (byte [] data, int start, int len, stringbuffer buf) { if (buf == null) buf = new stringbuffer (data.length * 3 / 2); int end = len - 3; int = start; int n = 0; while (i <= end) { int d = (((data [i]) & 0x0ff) << 16) | (((data [i+1]) & 0x0ff) << 8) | ((data [i+2]) & 0x0ff); buf.append (chartab [(d >> 18) & 63]); buf.append (chartab [(d >> 12) & 63]); buf.append (chartab [(d >> 6) & 63]); buf.append (chartab [d & 63]); += 3; if (n++ >= 14) { n = 0; buf.append ("\r\n"); } } if (i == start + len - 2) { int d = (((data [i]) & 0x0ff) << 16) | (((data [i+1]) & 255) << 8); buf.append (chartab [(d >> 18) & 63]); buf.append (chartab [(d >> 12) & 63]); buf.append (chartab [(d >> 6) & 63]); buf.append ("="); } else if (i == start + len - 1) { int d = ((data [i]) & 0x0ff) << 16; buf.append (chartab [(d >> 18) & 63]); buf.append (chartab [(d >> 12) & 63]); buf.append ("=="); } return buf; } static int decode (char c) { if (c >= 'a' && c <= 'z') return c - 65; else if (c >= 'a' && c <= 'z') return c - 97 + 26; else if (c >= '0' && c <= '9') return c - 48 + 26 + 26; else switch (c) { case '+': return 62; case '/': return 63; case '=': return 0; default: throw new runtimeexception (new stringbuffer("unexpected code: ").append(c).tostring()); } } /** decodes given base64 encoded string new byte array. byte array holding decoded data returned. */ public static byte [] decode (string s) { int = 0; bytearrayoutputstream bos = new bytearrayoutputstream (); int len = s.length (); while (true) { while (i < len && s.charat (i) <= ' ') i++; if (i == len) break; int tri = (decode (s.charat (i)) << 18) + (decode (s.charat (i+1)) << 12) + (decode (s.charat (i+2)) << 6) + (decode (s.charat (i+3))); bos.write ((tri >> 16) & 255); if (s.charat (i+2) == '=') break; bos.write ((tri >> 8) & 255); if (s.charat (i+3) == '=') break; bos.write (tri & 255); += 4; } return bos.tobytearray (); } /** * java org.xmlblaster.util.base64 helloworld * java org.xmlblaster.util.base64 -decode q2lbogeyvjvjrzlwwkqwblnhvnnirzhusudodmjuumxibljoyvcxbfbtzdbawggwtdnodgjdy2dzmjl1zedwdwrfmxbiv1zgzuhsbgjtumxardbutvm0d0p6netjq0e4yjnkbkxuahrirupzwvhomfpysstqr1jsylc4de16ndhmmljsylc4de16ndhmmjl5wnk1ngjxeenir0z6zedwevbnb2dqqzlywlhrkw== */ public static void main(string[] args) { if (args.length == 2) { if (args[0].equals("-decode")) { string base64 = args[1]; byte[] = mybase64.decode(base64); system.out.println("decoded '" + new string(back) + "'"); return; } } { string hello = args.length > 0 ? args[0] : "hello world"; string base64 = mybase64.encode(hello.getbytes()); byte[] = mybase64.decode(base64); system.out.println("before base64 '" + hello + "' base64='" + (new string(base64)) + "' after '" + new string(back) + "'"); } } }
and
public class mytrustmanager implements x509trustmanager { @override public void checkclienttrusted(x509certificate[] chain, string authtype) { } @override public void checkservertrusted(x509certificate[] chain, string authtype) { } @override public x509certificate[] getacceptedissuers() { return null; } }
after should ready go:
/* * return string authenticated ssl secured webserver call * */ public string sendhttpspostmessage(string username, string userpass, string url, string[] postvars) throws nosuchalgorithmexception, keymanagementexception, malformedurlexception, ioexception { stringbuffer sb = new stringbuffer(); final string serverauth = username + ":" + userpass; final string serverauthbase64 = mybase64.encode(serverauth.getbytes()); sslcontext sc = sslcontext.getinstance("tls"); sc.init(null, new trustmanager[] { new mytrustmanager() }, new securerandom()); httpsurlconnection.setdefaultsslsocketfactory(sc.getsocketfactory()); httpsurlconnection.setdefaulthostnameverifier(new myhostnameverifier()); httpsurlconnection con = (httpsurlconnection) new url(url).openconnection(); try { stringbuffer urlparameters = new stringbuffer(); string[] tmppair = null; (int = 0; < postvars.length; i++) { tmppair = postvars[i].tostring().split("="); if (i > 0) urlparameters.append("&" + tmppair[0] + "=" + urlencoder.encode(tmppair[1], "utf-8")); else urlparameters.append(tmppair[0] + "=" + urlencoder.encode(tmppair[1], "utf-8")); } con.setrequestmethod("post"); con.setrequestproperty("authorization", "basic " + serverauthbase64); con.setrequestproperty("content-type", "application/x-www-form-urlencoded"); con.setrequestproperty("content-length", "" + integer.tostring(urlparameters.tostring().getbytes().length)); con.setusecaches(false); con.setdooutput(true); con.setdoinput(true); dataoutputstream wr = new dataoutputstream (con.getoutputstream()); wr.writebytes (urlparameters.tostring()); wr.flush(); wr.close(); bufferedreader br = new bufferedreader(new inputstreamreader(con.getinputstream()), 8192 ); string line; while ( ( line = br.readline() ) != null ) { sb.append(line); } } catch(exception e) { log.e("sendhttpspostmessage", e.getlocalizedmessage()); } { if(con != null) { con.disconnect(); } } return sb.tostring(); }
Comments
Post a Comment