I used this code:
Code:
mWebViewVertreungsplan = (WebView)findViewById(R.id.webViewVertretung);
mWebViewVertreungsplan.setVisibility(View.VISIBLE);
mWebViewVertreungsplan.setWebViewClient(new WebViewClient());
// Enable Javascript
WebSettings webSettings = mWebViewVertreungsplan.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebViewVertreungsplan.loadUrl("Username: Pasword @ domain. com");
On the on some devices it works, but on others it wont work. I geht the error 401 unauthorized.
Funny enough i am working on a project that has to do with a "substitution plan" as well (dunno what the correct english translation is) xD
You have to put the credentials inside the url header, and they have to be Base64 encoded
I use jsoup library to read the values from a pw protected site, so putting things into header is done differently, but same principle:
[...]Jsoup.connect("domain.com").header("Authorization", "Basic " + encodedString).post()
encodedString is done like that:
String text ="unamewd";
byte[] data = null;
data = text.getBytes("UTF-8");
encodedString = Base64.encode(data, Base64.DEFAULT);
So only thing you would have to google is how to set url header for webview
Related
Have anyone used Jain Sip to do a Sip registration on Android?
I'm currently using Jain Sip on Android and I'm trying to get a SIP registration working.
I can put the registration SIP message together ok but after sending the message it seems to just get sent back to my application and my applications processRequest() method is run.
Here is the code I'm using :
Code:
public void init(TextView tv) throws Exception {
SipFactory sipFactory = null;
sipStack = null;
sipFactory = SipFactory.getInstance();
sipFactory.setPathName("gov.nist");
Properties properties = new Properties();
properties.setProperty("javax.sip.OUTBOUND_PROXY", getLocalIpAddress()+":8002" + "/"
+ ListeningPoint.UDP);
properties.setProperty("javax.sip.STACK_NAME", "Sip Test");
// Create SipStack object
sipStack = sipFactory.createSipStack(properties);
tv.setText("sipStack = " + sipStack);
headerFactory = sipFactory.createHeaderFactory();
addressFactory = sipFactory.createAddressFactory();
messageFactory = sipFactory.createMessageFactory();
lp = sipStack.createListeningPoint(getLocalIpAddress(),
8002, ListeningPoint.UDP);
sipProvider = sipStack.createSipProvider(lp);
sipOnOffFlag = true;
tv.append("\n jain sip stack started on " + getLocalIpAddress() + ":" + myPort + "/" + ListeningPoint.UDP);
sipProvider.addSipListener(this);
String fromName = "019078020";
String fromSipAddress = "216.234.148.28";
String fromDisplayName = "Donal";
String toSipAddress = "216.234.148.28";
String toUser = "16784732970";
String toDisplayName = "Server";
// create >From Header
SipURI fromAddress = addressFactory.createSipURI(fromName,
getLocalIpAddress());
Address fromNameAddress = addressFactory.createAddress(fromAddress);
fromNameAddress.setDisplayName(fromDisplayName);
FromHeader fromHeader = headerFactory.createFromHeader(
fromNameAddress, null);
// create To Header
SipURI toAddress = addressFactory
.createSipURI(toUser, toSipAddress);
Address toNameAddress = addressFactory.createAddress(toAddress);
toNameAddress.setDisplayName(toDisplayName);
ToHeader toHeader = headerFactory.createToHeader(toNameAddress,
null);
// create Request URI
SipURI requestURI = addressFactory.createSipURI(toUser,
"216.234.148.28");
// Create ViaHeaders
List<ViaHeader> viaHeaders = new ArrayList<ViaHeader>();
String ipAddress = lp.getIPAddress();
ViaHeader viaHeader = headerFactory.createViaHeader(ipAddress,
lp.getPort(),
lp.getTransport(), null);
// add via headers
viaHeaders.add(viaHeader);
// Create ContentTypeHeader
ContentTypeHeader contentTypeHeader = headerFactory
.createContentTypeHeader("application", "sdp");
// Create a new CallId header
CallIdHeader callIdHeader = sipProvider.getNewCallId();
// Create a new Cseq header
CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(1L,
Request.REGISTER);
// Create a new MaxForwardsHeader
MaxForwardsHeader maxForwards = headerFactory
.createMaxForwardsHeader(70);
// Create the request.
Request request = messageFactory.createRequest(requestURI,
Request.REGISTER, callIdHeader, cSeqHeader, fromHeader,
toHeader, viaHeaders, maxForwards);
// Create contact headers
SipURI contactUrl = addressFactory.createSipURI(fromName, getLocalIpAddress());
contactUrl.setPort(8002);
contactUrl.setLrParam();
// Create the contact name address.
SipURI contactURI = addressFactory.createSipURI(fromName, getLocalIpAddress());
contactURI.setPort(sipProvider.getListeningPoint(lp.getTransport())
.getPort());
Address contactAddress = addressFactory.createAddress(contactURI);
// Add the contact address.
contactAddress.setDisplayName(fromName);
contactHeader = headerFactory.createContactHeader(contactAddress);
request.addHeader(contactHeader);
// You can add extension headers of your own making
// to the outgoing SIP request.
// Add the extension header.
Header extensionHeader = headerFactory.createHeader("Expires",
"0");
request.addHeader(extensionHeader);
Log.d("SIP", "" + request.toString());
// Create the client transaction.
registerTid = sipProvider.getNewClientTransaction(request);
// send the request out.
registerTid.sendRequest();
dialog = registerTid.getDialog();
}
So the message gets built ok but when sendRequest() is run it doesn't appear to get sent to the server but rather back to my application and the applications processRequest method is run.
Should I be doing something extra with inviteTid or the dialog?
Do I need to create a socket or something to sent the request out?
Scratch that, got it working
Hey all,
I've been trying to get my app to authenticate with a webserver. (Not my own webserver).
But I've been having major issues. I've looked all over for a proper way to authenticate and have tried different methods, but I keep getting the same errors.
I either get:
1. 401 authorization required
2. 400 bad request
3. Cookie gets rejected because of illegal path attribute.
4. 200 ok, but I'm not getting the proper site info that pertains to the authorized part of the site.
This all depends on the different methods I try.
Currently, this is the code I am using:
Code:
private int auth(String username, String password) throws IOException {
String login = username + ":" + password;
String auth = Base64.encodeToString(login.getBytes("US-ASCII"), Base64.DEFAULT);
int response = 0;
URL url = new URL(esims_login);
URLConnection conn = url.openConnection() ;
conn.setRequestProperty("Set-cookie", "OBBasicAuth=fromDialog");
conn.addRequestProperty("Authorization", "Basic " + auth);
conn.connect();
return response;
}
I end up getting a bad request response using this method.
The OBBasicAuth=fromDialog is a header from the server that is supposed to pop up a dialog that receives the username and password. So I added that to the initial request.
So my question is, what am I not doing/doing wrong?! I've been trying to accomplish this for weeks.
have you tried to trim the base64 encoded string ?
Code:
conn.addRequestProperty("Authorization", "Basic " + auth.trim());
Well, trimming the auth string helped, but now I am getting an expired session.
Can't get rid of this error:
android.database.sqlite.SQLiteException: near "s": syntax error: , while compiling:
Select correct from answers where correct = 'Between the airplane's climb angle and the horizon.'
Obviously, it's finding the single quote in ( airplane's ) and considering that the end of the statement.
I've tried:
correct.replaceAll(" ' ", " ''' "); //replace 1 with 3
correct.replaceAll(" ' ", " '' "); // replace 1 with 2
correct.replaceAll(" ' ", " "); // replace 1 with space
(NOTE: the spaces are NOT in the code, I just did that to make it readable)
I have no idea what's going on, IMO, it should work. Maybe I need to try:
String single = "'"; // single '
String double = "''" // double ''
correct.replaceAll(single, double); // ????
Everything I"ve read about sqlite3 is to replace one with two....
TIA,
Roots
\'
\ is the escape character for most languages
so airplane's would be airplane\'s
Also, are you binding your queries with the "question mark" bind?
I'll try the escape and post back later. There are 1,000 rows in the database and I"m pulling a random subset of that, so it's not that often I get one of those situations.
I'm not sure what you mean by "binding with ?" Isn't that what you use for bind variable unknown at runtime? I know my bind variables and just use it in my dbquery. Please enlighten me...always happy to learn something new
Sample code...answerOne would contain the single quote that's killing me
Code:
Cursor c;
c = myDataBase.rawQuery("Select correct from answers where correct = '" + answerOne + "'", null);
if(c.moveToFirst())
answer = "1";
c.close();
binding with question marks should take care of escaping for you.
Basically the question mark is a place holder for a variable in the query.
What you are doing is manually creating the query string. This is considered bad practice these days especially with regards to security. Mostly because it opens up the DB to a SQL injection attack.
So instead of using the rawQuery just use query and you can put a ? in and android will substitute the value for you, all properly escaped:
Code:
String tableName = "answers";
String selectArgs = "correct=[COLOR="Red"]?[/COLOR]";
// if answerOne is string dont need String.valueOf
String[] selectVals = { String.valueOf ( answerOne ) };
String[] columnsProjection= new String[] {"correct" };
Cursor c = db.query(tableName, columnsProjection, selectArgs,selectVals,null);
So in that code the OS will replace the ? in selectArgs with the values in selectVals
This may seem like more writing at first but once you get in the habit it will be easy, reliable and more secure. It also allows you to bind multiple variables to mutiple question marks. It just binds then in the order it gets them.
so something like this:
Code:
String answerOne= "one";
String selectArgs = "correct=? AND age=? AND smiling=?";
String[] selectVals = { answerOne, "21", "yes" };
Ok, I'll try it. There are about 50 different queries in this program...for some reason I just decided to do a rawQuery on this one. I'll change it to "db.query(table name, new String[] {}....yada, yada).
Because, it just crashed and I decided to come back here and check for a solution.
Thank you very much!!!
Roots
Glad to be of help, just remember to hit the thanks booton ya Rooster
Still getting the error
Example: column is in table as text. Say it's equal to:
The driver's last name
Error comes back as "syntax error near 's' when compiling select correct from answers where correct = 'The driver's last name'
That single quote in driver's is killing my SQL.
Hallo,
I have the following function in my AsyncTask:
Code:
private SSLContext trustCert() throws Exception {
SSLContext context = null;
context = SSLContext.getInstance("TLS");
// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = this.context.getResources().openRawResource(R.raw.cert);
Certificate ca = cf.generateCertificate(caInput);
caInput.close();
// Create a KeyStore containing our trusted CAs
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
context.init(null, tmf.getTrustManagers(), null);
return context;
}
In the doInBackground-Function im loading some resources from my server with a self-signed certificate:
Code:
SSLContext sslContext = this.trustCert();
HttpsURLConnection conn = (HttpsURLConnection) address.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());
......
conn.connect(); //here i get the error
And sometimes (!) I get following Error on the last line of the code posted:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
But why?
..
anyone?
Hi
Are you sure your sever is well configured ? It seems that there are some intermediate certificates missing from the certificate chain but google "Trust anchor not found" you'll find some helpful links
TheDoubleTap said:
Hi
Are you sure your sever is well configured ? It seems that there are some intermediate certificates missing from the certificate chain but google "Trust anchor not found" you'll find some helpful links
Click to expand...
Click to collapse
I have met this issue before. My solution is setting the verifier host and ssl factory before you setting up the https utl connection
e.g. :
private static void trustAllHosts() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(notVerify);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
}
add this method before your https connection create method. Hope it can help you.
Look at my code, I'm already doing that..
I'm trying to send data via Http but I keep getting this error: No encoding found. Expected encoding 'utf-8' to be present in message header. I tried adding:
connection.setRequestProperty("charset","utf-8"); but it still didn't work.
The full code is:
Java:
HttpURLConnection connection;
try {
//Open a new URL connection
connection = (HttpURLConnection) new URL(params[0])
.openConnection();
//Defines a HTTP request type
connection.setRequestMethod("POST");
//Sets headers: Content-Type
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset","utf-8");
//Add POST data in JSON format
JSONObject jsonParam = new JSONObject();
try {
jsonParam.put("Count", Integer.parseInt(Data));
} catch (JSONException e) {
e.printStackTrace();
}
//Create a writer object and make the request
OutputStreamWriter outputStream = new OutputStreamWriter(connection.getOutputStream());
outputStream.write(jsonParam.toString());
outputStream.flush();
outputStream.close();
Thanks so much!
Stack overflow is a better place for programming questions than here I suspect...
This looks like the same question. There's a good-looking answer there.
Java send http POST with UTF-8
I need to send HTTP POST with Google FCM. With code below, it's OK to send English message but Chinese characters. I did many trials by adding UTF-8 here and there... Need help. The payload of my
stackoverflow.com