HttpURLconnection connection failure with non .com website - java

I have been trying to connect my android app to php server.I made a php server echo "Connection success" so that I could retrieve the same text and display it in Alertbox in my android application.I have a website with a .cf and the app shuts down every time I connect.
I checked my code found nothing wrong, then I tried a .com website, and the app was successfully able to retrieve the html form of whatever was displayed on the page.So is there something that prevents HttpURLconnection form connecting to non .com websites.
Here is the code.
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}//takes context as an argument
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://www.thejoint.cf/test.php";
if(type.equals("login")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);//what does the url object have
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result+=line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
Log.i("info",result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}

So is there something that prevents HttpURLconnection form connecting to non .com websites ?
you create a regex :
String expression = "[^"]+\.com" ;
and test if your url matches with it :
if(your_url.matches(expression)){
// your url end with .com , do what you want
}else{
// your url doesn't end with .com , do what you want
}

Related

Trying to redirect the user to new page after login in android studio

I'm having problem with redirecting user to new page after the login authentication. If I try to direct my next page in postexecute method it works with
Intent home = new Intent(context,Home_page.class);
context.startActivity(home);
but then it directs it to next page even if the login credentials are wrong. How do i modify my code so that it first check the login credentials and then links the next page with login button.
class background_login extends AsyncTask<String, Void,String>
{
AlertDialog dialog;
Context context;
public background_login (Context context)
{
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
}
#Override
protected String doInBackground(String... params)
{
String results="";
String user_name = params[0];
String password = params[1];
String connstr= "url";
try
{
URL url= new URL(connstr);
HttpURLConnection http =(HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream ops = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ops,"UTF-8" ));
String data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")
+"&&"+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
writer.write(data);
writer.flush();
writer.close();
ops.close();
InputStream ips = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ips, "ISO-8859-1"));
String line ="";
while ((line = reader.readLine()) !=null)
{
results+=line;
}
reader.close();
ips.close();
http.disconnect();
return results;
} catch (MalformedURLException e) {
results= e.getMessage();
} catch (IOException e) {
results=e.getMessage();
}
return results;
}
}
In onPostExecute you should check request response data like json, xml etc. and than call specific activity or provide error message.
AsyncTask json example: Get JSON in AsyncTask Android
#Override
protected void onPostExecute(JSONObject jsonData){
try {
boolean login = jsonData.getBoolean('isLoginSuccess');
if(login){
String keyToAccessLater = jsonData.getString('accessKey');
Intent home = new Intent(((Activity)context), Home_page.class);
((Activity)context).startActivity(home);
else
...
...
}

PHP and AlertDialog not in sync on Android

I'm currently building a simple login Android app using a tutorial on YouTube that fetches data from a database and lets the user login. However, when I click the login button, regardless of what the input is, it tells me that the login has been successful. Below is the Java code where the data is entered and the PHP code to connect to the database, every time login is clicked the AlertDialog will pop up saying 'Login successful'. I want it to display 'Login not successful' if the data the user enters is incorrect, can somebody show me how? Thanks
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "";
if (type.equals("Login")) {
try {
String userName = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("userName", "UTF-8")+"="+URLEncoder.encode(userName, "utf-8")+"&"
+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "utf-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result ="";
String line ="";
while ((line = bufferedReader.readLine()) != null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login status: ");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
====
<?php
require "conn.php";
$userName = $_POST["userName"];
$password = $_POST["password"];
$mysql_qry = "select * from database where userName like '$userName' and password like '$password';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
echo "Successful login";
}
else{
echo "Login not successful";
}
In your conn.php file
$dbname = "";
$username = "";
$password = "";
$server = "";
This should not be empty.
Fill it with appropriate data

Android connecting with MySql using AsyncTask and return data in form of JSON or String

I have been working to connect MySql database to my android app and searched on internet. Some of the solutions worked with one problem. The problem is that the function returns data in the form which is String and the content of String is :
[{"id":1,"username":"admin","password":"root","email":"admin#localhost.com","fullname":"Site Admin"}]
But I want the data in form of some sort of array through which I can get all the user data like email , fullname separately. I tried to implement a function but that didn't work. Following is the code:
BackgroundWorker.java
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
String tresult;
BackgroundWorker (Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String username = params[1];
String password = params[2];
String login_url = "http://192.168.1.18/myproj/api/query1.php";
if (type.equals("login")){
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"+
URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String line="";
String result="";
while((line = bufferedReader.readLine())!= null){
result+=line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
tresult = result;
//return tresult;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
BackgroundWorker is a class which works in background and connect with database. And in MainActivity it is called as following:
MainActivity
public void onLogin(View view, String user, String pass){
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type,user,pass);
}
Calling of function:
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = user_edittext.getText().toString();
String password = pass_edittext.getText().toString();
onLogin(v,username,password);
}
});
In short I want to return the variable result or tresult from protected void onPostExecute(String result) in my MainActivity and convert it to Array. Thankyou! waiting for experts opinion.
It seems you have two issues:
Converting a Json string to a more friendly format
Returning this friendly format to another activity
on 1:
There is no built in way to parse JSON strings in Java but lots of easy library options available - take a look at How to parse JSON in Java where these are discussed.
on 2:
In general data is converted to a bundle and returned to your main activity as part of the intent system

If we are typing wrong field in the username & pass. It shows a login failure alert, but its calling the next Activity. Tow to fix this?

This code is for my login Activity.
I have used an Intent to call the next page in the onPostExecute() method, but it could not work properly.
If we are typing a wrong value in the username & pass, it shows the login failure alert but it calls the next Activity.
How to fix this?
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://techblog.96.lt/login.php";
if (type.equals("Login")) {
try {
String username = params[1];
String pass = params[2];
URL url = new URL(login_url);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
OutputStream outputStream = httpUrlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(pass, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpUrlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpUrlConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Success");
}
#Override
protected void onPostExecute(String result) {
Intent i = new Intent(context, NewActivity.class);
context.startActivity(i);
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate (Void...values)
{
super.onProgressUpdate(values);
}
}
onPostExecute will always start the next Activity regardless of the value of the String result.
You need to check that value for whatever determines if you've successfully logged in. Also check it for null since that is also being returned by doInBackground
You should use onPostExecute method. You need to check response code inside your doInBackground method and depending on the result you need to return an appropriate String. Then inside onPostExecute check that response from doInBackground and take appropriate actions.

Login not successful on MySQL database from android app

I have created an android app that logins into a MySQL database but I don't receive any results. The 'result' variable in the alert dialog box in backgroundWorker.java (function "onPostExecute") returns null, can anyone solve this problem?
BackgroundWorker.java`
public class BackgroundWorker extends
AsyncTask<String,String,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx)
{
context =ctx;
}
#Override
protected String doInBackground(String... params) {
String type=params[0];
String login_url="192.168.10.9/login.php";
if(type.equals("login"))
{
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog=new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String Result) {
Log.i("ok", "Result " + Result);
alertDialog.setMessage(Result);
alertDialog.show();
}
CheckConn.java
public class CheckConn extends AppCompatActivity {
EditText user;
EditText pass;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.check_conn);
user = (EditText) findViewById(R.id.et_u);
pass = (EditText) findViewById(R.id.et_p);
Button press = (Button) findViewById(R.id.btn_login);
press.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onLogin();
}
});
}
public void onLogin()
{
String username= user.getText().toString();
String password=pass.getText().toString();
String type="login";
BackgroundWorker backgroundWorker=new BackgroundWorker(this);
backgroundWorker.execute(type,username,password);
}
}
connection.php
<?php
$mysql_usernmae="root";
$mysql_password="*****";
$db="map";
$db= new mysqli('localhost',$mysql_usernmae,$mysql_password,$db);
?>
login.php
<?php
require "connection.php";
$user_name=$_POST["user_name"];
$user_pass=$_POST["password"];
$mysql_qry="select * from user_info where user_name like
'$user_name' and user_password like 'user_pass';";
$result=mysqli_query($db,$mysql_qry);
if (mysqli_num_rows($result) > 0)
{
echo "login Successsss";
}
else
{
echo "faileddddd Booooo";
}
?>
`
why you don't ejecute first your login.php file in the browser, harcode the values for user_name and user_pass, and check if the connection is working on server side,
after that you can check if your user and pass are coming from android app, I must assume you have a database with some data in the table you are making the query, also check if the name of database, table, query are correct, you can check with MySQL workbench if the query works and is returning some result.

Categories