I am making a login app to retreive some information from the link that appears in the code. My problem is that I'm getting a "400 Bad request. The request could not be understood by server due to malformed syntax" in the Log file.
Besides, that link handles RC4_128 with SHA1 for authentication and RSA for key exchange but don't really know where I can apply those protocols in my code.
Thanks for your help!
This is my code:
public class POPLogin extends Activity {
private EditText usr, pass;
private Button submitButton;
private CharSequence notify;
private String res, resp;
private final String link = "https://pop-portal.tut.fi/portal/page/portal/POP-portaali/20Opinnot/22Omat%20suoritukset";
private URL url;
public static boolean isNetworkAvailable(Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poplogin);
usr = ((EditText) findViewById(R.id.usernameField));
pass = ((EditText) findViewById(R.id.passwordField));
submitButton = (Button) findViewById(R.id.submitButton);
submitButton.getBackground().setColorFilter(new LightingColorFilter(0x00FFB90F, 0xFFAA0000));
/*
* This method controls the login button so that the correct
* information is sent to the server.
*/
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isNetworkAvailable(getApplicationContext())) { // If there is an Internet connection available
/*
* A new thread is created from the main one
* to separate the login process (AsyncTask, https operations).
*/
new Thread(new Runnable() {
public void run() {
try {
url = new URL(link);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// Create the SSL Connection
SSLContext sc;
sc = SSLContext.getInstance("TLS");
sc.init(null, null, new java.security.SecureRandom());
conn.setSSLSocketFactory(sc.getSocketFactory());
// SSL Authentication
String userpass = usr.getText().toString() + ":" + pass.getText().toString();
String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.DEFAULT);
conn.setRequestProperty("Authorization", basicAuth);
Log.i("NOTIFICATION", "All SSL parameters set");
// Set timeout and method
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("POST");
conn.setDoInput(true); // Flag indicating this connection is used for output (POST)
conn.connect();
Log.i("NOTIFICATION", "Connection request sent");
// Check HTTP Response Code
int status = conn.getResponseCode();
InputStream is;
if (status >= 400 ) {
is = conn.getErrorStream();
} else {
is = conn.getInputStream();
}
Log.i("NOTIFICATION", "HTTP Code Checked");
// Receives the answer
resp = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
while((res = rd.readLine()) != null) {
resp += res;
}
Log.i("NOTIFICATION", "Answer received");
Log.i("CODE", resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} else {
notify = "Internet Connection not available";
}
if(notify != null) {
Toast toast = Toast.makeText(getApplicationContext(), notify, Toast.LENGTH_SHORT);
toast.show();
notify = null;
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.poplogin, menu);
return true;
}
}
Related
I want to start an activity and give out a Toast message after I parsed a JSON response, well as you can't do that while a Dialog is open, I am using a DialogListener, which actually works fine, but not when it gets called in the parseJSON method.
public class Pop_Forgot_PW extends AppCompatDialogFragment{
......
sendResetMail();
private void sendResetMail()
{
final String url = "someURL";
new Json(new Json.Callback() {
#Override
public void run(String result) {
parseJSON(result);
}
}).checkJsonFile(url, getContext());
}
//Now in an non-activity class
public class Json {
public void checkJsonFile(final String url, final Context context) {
new Thread(new Runnable() {
public void run() {
String result;
String line;
try {
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setReadTimeout(5000);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
boolean redirect = false;
// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
if (redirect) {
// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
// open the new connnection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
}
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
result = sb.toString();
callback.run(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
//Back in the Pop_Up
public void parseJSON(String JSON) {
try {
JSONObject jsonObject = new JSONObject(JSON);
error = jsonObject.getInt("error_code");
switch (error) {
case 0:
toastText = getString(R.string.email_sent);
break;
case 1:
toastText = getString(R.string.no_account);
break;
}
listener.showToast(toastText);
dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void setListener(DialogListener listener) {
this.listener = listener;
}
public interface DialogListener
{
void showToast(String toastText);
}
I already tried the runOnUIThread, but it doesn't help.
Thank you very much in advance
Solved it by putting all the stuff in an activity an not in the DialogFragment.
Thank you to everyone :)
I am developing an android app.
In a specific part of my code, the else option is always executed, even though the if statement is satisfied. Any help is highly appreciated.
Here is my code:
PHP:
<?php
error_reporting(0);
include 'conexao.php';
$usuario = $_POST["username"];
$senha = $_POST["password"];
$result = mysql_query("select * from login where usuario = '" . $usuario . "' and senha = '" . $senha . "';");
$num_rows = mysql_num_rows($result);
if ($num_rows == 0) {
echo 'false';
} else if ($num_rows == 1) {
echo 'true';
} else {
echo 'nenhum';
}
?>
and my Java :
EditText txtusuario, txtsenha;
Button btnlogin;
public static final int CONNECTION_TIMEOUT=10000;
public static final int READ_TIMEOUT=15000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtusuario = (EditText) findViewById(R.id.txtusuario);
txtsenha = (EditText) findViewById(R.id.txtsenha);
btnlogin = (Button) findViewById(R.id.btnlogin);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get text from email and passord field
final String username = txtusuario.getText().toString();
final String password = txtsenha.getText().toString();
// Initialize AsyncLogin() class with email and password
new AsyncLogin().execute(username,password);
}
});
}
private class AsyncLogin extends AsyncTask<String, String, String>
{
ProgressDialog pdLoading = new ProgressDialog(LoginActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://rhynotcc.hol.es/teste/login.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username", params[0])
.appendQueryParameter("password", params[1]);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "exception";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return(result.toString());
} else {
return("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
String teste = "true";
if(result.equals(teste)) {
//Notificação para saber o resultado do login
int a = 0;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(LoginActivity.this);
mBuilder.setSmallIcon(R.drawable.escavadeira);
mBuilder.setContentTitle("Notificação");
mBuilder.setContentText("Conexão deu certo caralho" + result);
NotificationManager mNot = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNot.notify(a, mBuilder.build());
} else {
int a = 0;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(LoginActivity.this);
mBuilder.setSmallIcon(R.drawable.escavadeira);
mBuilder.setContentTitle("Notificação");
mBuilder.setContentText("Deu errado" + result);
NotificationManager mNot = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNot.notify(a, mBuilder.build());
}
}
}
the result in my notification is 'deu errado true' when true should been the if statement, and I have already tried result.equals("true")
if ($num_rows == 0) {
echo 'false';
} else if ($num_rows == 1) {
echo 'true';
} else {
echo 'nenhum';
}
instead of this make sure your code should be just like
if ($num_rows) {
echo 'false';
} else {
echo 'nenhum';
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
String teste = "true";
int a = 0;
NotificationCompat.Builder mBuilder = new
NotificationCompat.Builder(LoginActivity.this);
mBuilder.setSmallIcon(R.drawable.escavadeira);
mBuilder.setContentTitle("Notificação");
if (result.equals(teste)) {
//Notificação para saber o resultado do login
mBuilder.setContentText("Conexão deu certo caralho" + result);
} else {
mBuilder.setContentText("Deu errado" + result);
}
NotificationManager mNot = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNot.notify(a, mBuilder.build());
}
I am trying to get my webview to show a page that is only accesible after i am logged in. but whatever i try i cant get past the login url.
How can i open/show the SEND_VISUM_URL after i login.
this is what i have so far:
String LOGIN_URL = "http://10.35.50.125/BCS/index.php?module=";
String SEND_VISUM_URL = "http://10.35.50.1/BCS/index.php?module=ScanVisa&Action=save";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView)findViewById(R.id.webviewer);
webView.loadUrl(LOGIN_URL);
cookieManager = new CookieManager();
Button login = (Button) findViewById(R.id.PostData);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new loginTask().execute(getLoginData());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public class loginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String loginData = params[0];
String text = "";
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL login_url = new URL(LOGIN_URL);
// getting cookies:
URLConnection conn = login_url.openConnection();
conn.connect();
// setting cookies
cookieManager.storeCookies(conn);
cookieManager.setCookies(login_url.openConnection());
cookiestring = cookieManager.toString();
Log.d("Cookie in logintask:", cookiestring);
conn.getContent();
conn.setDoOutput(true);
conn.setConnectTimeout(3000);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
try {
wr.write(loginData); //post
wr.flush();
} catch (Exception e) {
e.printStackTrace();
}
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (line.length() > 0) {
sb.append(line + "\n");
if (line == null) {
continue;
}
}
}
text = sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (reader != null) reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return text;
}
protected void onPostExecute(String line) {
if (!line.contains("I107")) { //I107 is an error code that is returend when a login failed
Toast.makeText(getBaseContext(), "Login succesfull", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
}
}
}
public void setCookies(URLConnection conn) throws IOException {
// let's determine the domain and path to retrieve the appropriate cookies
URL url = conn.getURL();
String domain = getDomainFromHost(url.getHost());
String path = url.getPath();
Map domainStore = (Map)store.get(domain);
if (domainStore == null) return;
StringBuffer cookieStringBuffer = new StringBuffer();
Iterator cookieNames = domainStore.keySet().iterator();
while(cookieNames.hasNext()) {
String cookieName = (String)cookieNames.next();
Map cookie = (Map)domainStore.get(cookieName);
// check cookie to ensure path matches and cookie is not expired
// if all is cool, add cookie to header string
if (comparePaths((String)cookie.get(PATH), path) && isNotExpired((String)cookie.get(EXPIRES))) {
cookieStringBuffer.append(cookieName);
cookieStringBuffer.append("=");
cookieStringBuffer.append((String)cookie.get(cookieName));
if (cookieNames.hasNext()) cookieStringBuffer.append(SET_COOKIE_SEPARATOR);
}
}
try {
conn.setRequestProperty(COOKIE, cookieStringBuffer.toString());
} catch (java.lang.IllegalStateException ise) {
IOException ioe = new IOException("Illegal State! Cookies cannot be set on a URLConnection that is already connected. "
+ "Only call setCookies(java.net.URLConnection) AFTER calling java.net.URLConnection.connect().");
throw ioe;
}
}
any help would be greatly appreciated!
all of a sudden my mobile device can't connect to the local server anymore. async tasks are not executed and i just can't figure out why. slowly i'm getting really desperate because in my opinion i didn't change anything to cause this.
as an example, this is a background task which is not working
public class Login extends AsyncTask<String, Void, String>{
private String loginUrl = "http://...";
private int loginSuccess = 0;
public String getToken(String fromJson) throws JSONException {
JSONObject json = new JSONObject(fromJson);
if(json.has("api_authtoken")) {
loginSuccess = 1;
String appToken = json.getString("api_authtoken");
return appToken;
}
else {
return json.toString();
}
}
public String doInBackground(String... arg0) {
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String authToken;
try {
// get logged in to get the api_authtoken
String email = (String) arg0[0];
String password = (String) arg0[1];
URL url = new URL(loginUrl);
// Create the request and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
//put values of edittexts into json-Object
JSONObject data = new JSONObject();
try {
data.put("email", email);
data.put("password", password);
} catch(JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data.toString());
wr.flush();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
//read server response
while((line = reader.readLine()) != null) {
sb.append(line);
}
//receive server "answer"
try {
return getToken(sb.toString());
}catch(JSONException e) {
Log.e("LOG", "unexpected JSON exception", e);
e.printStackTrace();
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
//return sb.toString();
return null;
}
catch(IOException e) {
Log.e("LoginTask", "Error ", e);
// If the code didn't successfully get the data, there's no point in attempting
// to parse it.
//forecastJsonStr = null;
return null;
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
//Log.v("RESULT", result);
if(result == null) {
CharSequence text = "no internet connection";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
if(loginSuccess == 0) {
// if the request wasn't successful
// give user a message via toast
CharSequence text = "wrong password or user. please try again";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
else {
// save token in shared preferences
SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
SharedPreferences.Editor editorToken = tokenPref.edit();
editorToken.putString(getString(R.string.saved_auth_token), result);
editorToken.commit();
//save login status = 1 in shared preferences
SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
SharedPreferences.Editor editorLogin = loginPref.edit();
editorLogin.putString(getString(R.string.saved_login), "1");
editorLogin.commit();
Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(mapsIntent);
}
}
}
HttpClient is not supported any more in sdk 23. You have to use URLConnection or downgrade to sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')
If you need sdk 23, add this to your gradle:
android {
useLibrary 'org.apache.http.legacy'
}
HttpClient won't import in Android Studio
You should think about using a HTTP library, there is a bunch of them on internet, some are really easy to use, optimize and errorless.
For example, Volley (made by Google, I really like this one), okHttp or Picasso (for image).
You should take a look at this.
If you want to send (output), for example with POST or PUT requests you need to use this :-
urlConnection.setDoOutput(true);
In your code :-
public class Login extends AsyncTask<String, Void, String>{
private String loginUrl = "http://...";
private int loginSuccess = 0;
public String getToken(String fromJson) throws JSONException {
JSONObject json = new JSONObject(fromJson);
if(json.has("api_authtoken")) {
loginSuccess = 1;
String appToken = json.getString("api_authtoken");
return appToken;
}
else {
return json.toString();
}
}
public String doInBackground(String... arg0) {
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String authToken;
try {
// get logged in to get the api_authtoken
String email = (String) arg0[0];
String password = (String) arg0[1];
URL url = new URL(loginUrl);
// Create the request and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true); // HERE
//put values of edittexts into json-Object
JSONObject data = new JSONObject();
try {
data.put("email", email);
data.put("password", password);
} catch(JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data.toString());
wr.flush();
urlConnection.connect();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
//read server response
while((line = reader.readLine()) != null) {
sb.append(line);
}
//receive server "answer"
try {
return getToken(sb.toString());
}catch(JSONException e) {
Log.e("LOG", "unexpected JSON exception", e);
e.printStackTrace();
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
//return sb.toString();
return null;
}
catch(IOException e) {
Log.e("LoginTask", "Error ", e);
// If the code didn't successfully get the data, there's no point in attempting
// to parse it.
//forecastJsonStr = null;
return null;
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
//Log.v("RESULT", result);
if(result == null) {
CharSequence text = "no internet connection";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
if(loginSuccess == 0) {
// if the request wasn't successful
// give user a message via toast
CharSequence text = "wrong password or user. please try again";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
else {
// save token in shared preferences
SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
SharedPreferences.Editor editorToken = tokenPref.edit();
editorToken.putString(getString(R.string.saved_auth_token), result);
editorToken.commit();
//save login status = 1 in shared preferences
SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
SharedPreferences.Editor editorLogin = loginPref.edit();
editorLogin.putString(getString(R.string.saved_login), "1");
editorLogin.commit();
Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(mapsIntent);
}
}
}
I am making a login app to retreive some information from the link that appears in the code. My problem is that I'm getting a "400 Bad request. Your browser sent a request that this server could not understand. [...] Server at idp.tut.fi Port 443" in the Log file.
Besides, that link handles RC4_128 with SHA1 for authentication and RSA for key exchange but don't really know where I can apply those protocols in my code.
Thanks for your help!
This is my code:
public class POPLogin extends Activity {
private EditText usr, pass;
private Button submitButton;
private CharSequence notify;
private String res, resp;
private final String link = "https://idp.tut.fi/idp/Authn/UserPassword";
private URL url;
public static boolean isNetworkAvailable(Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poplogin);
usr = ((EditText) findViewById(R.id.usernameField));
pass = ((EditText) findViewById(R.id.passwordField));
submitButton = (Button) findViewById(R.id.submitButton);
submitButton.getBackground().setColorFilter(new LightingColorFilter(0x00FFB90F, 0xFFAA0000));
/*
* This method controls the login button so that the correct
* information is sent to the server.
*/
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isNetworkAvailable(getApplicationContext())) { // If there is an Internet connection available
/*
* A new thread is created from the main one
* to separate the login process (AsyncTask, https operations).
*/
new Thread(new Runnable() {
public void run() {
try {
url = new URL(link);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// Create the SSL Connection
SSLContext sc;
sc = SSLContext.getInstance("TLS");
sc.init(null, null, new java.security.SecureRandom());
conn.setSSLSocketFactory(sc.getSocketFactory());
// SSL Authentication
String userpass = usr.getText().toString() + ":" + pass.getText().toString();
String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.DEFAULT);
conn.setRequestProperty("Authorization", basicAuth);
Log.i("NOTIFICATION", "All SSL parameters set");
// Set timeout and method
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("POST");
conn.setDoInput(true); // Flag indicating this connection is used for output (POST)
conn.connect();
Log.i("NOTIFICATION", "Connection request sent");
// Check HTTP Response Code
int status = conn.getResponseCode();
InputStream is;
if (status >= 400 ) {
is = conn.getErrorStream();
} else {
is = conn.getInputStream();
}
Log.i("NOTIFICATION", "HTTP Code Checked");
// Receives the answer
resp = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
while((res = rd.readLine()) != null) {
resp += res;
}
Log.i("NOTIFICATION", "Answer received");
Log.i("CODE", resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} else {
notify = "Internet Connection not available";
}
if(notify != null) {
Toast toast = Toast.makeText(getApplicationContext(), notify, Toast.LENGTH_SHORT);
toast.show();
notify = null;
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.poplogin, menu);
return true;
}
}
If you got an HTTP error code it is proof that your HTTPS and therefore SSL setup is working perfectly.
The problem is in the data you're sending. It looks like you need to use a java.net.Authenticator rather than try to do it by hand.