0

I am trying to make an authentication system in my Android application using PHP, JSON and MySQL but I keep getting connection to url refused.

PS. This is my first time using this method and it was based on a tutorial, of course I would appreciate any other suggestions

This is my Register Activity class written in JAVA:

public class RegisterActivity extends Activity {

private Button btn_register;
private TextView btn_login;

private EditText et_login;
private EditText et_pass, et_confirm_pass;

JSONParser jsonParser = new JSONParser();

// url to create new product
private static String url_create_user = "http://172.16.21.5/ladies_api/register.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    btn_login = (TextView) findViewById(R.id.tv_login);
    btn_register = (Button) findViewById(R.id.btn_reg);

    et_login = (EditText) findViewById(R.id.et_username);
    et_pass = (EditText) findViewById(R.id.et_password);
    et_confirm_pass = (EditText) findViewById(R.id.et_c_password);

    btn_register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String login = et_login.getText().toString();
            String pwd = et_pass.getText().toString();
            String c_pwd = et_confirm_pass.getText().toString();
            /** REGISTER USER, GO TO HOME */
            //new CreateNewUser().execute();
            AsyncDataClass asyncRequestObject = new AsyncDataClass();

            asyncRequestObject.execute(url_create_user, login, pwd);
        }
    });

    btn_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
        }
    });
}

private class AsyncDataClass extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... params) {
        HttpParams httpParameters = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);

        HttpConnectionParams.setSoTimeout(httpParameters, 5000);

        HttpClient httpClient = new DefaultHttpClient(httpParameters);

        HttpPost httpPost = new HttpPost(params[0]);

        String jsonResult = "";

        try {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

            nameValuePairs.add(new BasicNameValuePair("username", params[1]));

            nameValuePairs.add(new BasicNameValuePair("pwd", params[2]));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpClient.execute(httpPost);

            jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

            System.out.println("Returned Json object " + jsonResult.toString());

        } catch (ClientProtocolException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return jsonResult;
    }
    @Override

    protected void onPreExecute() {

        super.onPreExecute();

    }

    @Override

    protected void onPostExecute(String result) {

        super.onPostExecute(result);

        System.out.println("Resulted Value: " + result);

        if(result.equals("") || result == null){

            Toast.makeText(RegisterActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();

            return;

        }

        int jsonResult = returnParsedJsonObject(result);

        if(jsonResult == 0){

            Toast.makeText(RegisterActivity.this, "Invalid username or password or email", Toast.LENGTH_LONG).show();

            return;

        }

        if(jsonResult == 1){

            Intent intent = new Intent(RegisterActivity.this, MainActivity.class);

            startActivity(intent);

        }

    }

private StringBuilder inputStreamToString(InputStream is) {

    String rLine = "";

    StringBuilder answer = new StringBuilder();

    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    try {

        while ((rLine = br.readLine()) != null) {

            answer.append(rLine);

        }

    } catch (IOException e) {

        e.printStackTrace();

    }

    return answer;

}
private int returnParsedJsonObject(String result){

        JSONObject resultObject = null;

        int returnedResult = 0;

        try {

            resultObject = new JSONObject(result);

            returnedResult = resultObject.getInt("success");

        } catch (JSONException e) {

            e.printStackTrace();

        }

        return returnedResult;

    }
}
}

This is JASONParser class

public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {

    }

    // return JSON String
    return jObj;

}
}

And here's the logCat

04-29 02:04:05.803 15719-15719/hivemind.com.ladies D/ViewRootImpl: ViewPostImeInputStage processPointer 0 04-29 02:04:05.983 15719-15719/hivemind.com.ladies D/ViewRootImpl: ViewPostImeInputStage processPointer 1 04-29 02:04:05.983 15719-17866/hivemind.com.ladies I/System.out: Thread-10038(ApacheHTTPLog):isSBSettingEnabled false Thread-10038(ApacheHTTPLog):isShipBuild true 04-29 02:04:05.993 15719-17866/hivemind.com.ladies I/System.out: Thread-10038(ApacheHTTPLog):getDebugLevel 0x4f4c Thread-10038(ApacheHTTPLog):Smart Bonding Setting is false Thread-10038(ApacheHTTPLog):SmartBonding Setting is false, SHIP_BUILD is true, log to file is false, DBG is false, DEBUG_LEVEL (1-LOW, 2-MID, 3-HIGH) is 1 04-29 02:04:08.993 15719-17866/hivemind.com.ladies I/System.out: AsyncTask #5 calls detatch() 04-29 02:04:08.993 15719-17866/hivemind.com.ladies W/System.err: org.apache.http.conn.HttpHostConnectException: Connection to http://172.16.21.5 refused at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:248) at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:172) at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:130) at org.apache.http.impl.client.DefaultRequestDirector.executeOriginal(DefaultRequestDirector.java:1337) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:705) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:578) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:494) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:472) at hivemind.com.ladies.Authentication.RegisterActivity$AsyncDataClass.doInBackground(RegisterActivity.java:116) at hivemind.com.ladies.Authentication.RegisterActivity$AsyncDataClass.doInBackground(RegisterActivity.java:90) at android.os.AsyncTask$2.call(AsyncTask.java:295) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818) Caused by: java.net.ConnectException: failed to connect to /172.16.21.5 (port 80) after 5000ms: isConnected failed: EHOSTUNREACH (No route to host) at libcore.io.IoBridge.isConnected(IoBridge.java:234) at libcore.io.IoBridge.connectErrno(IoBridge.java:171) at libcore.io.IoBridge.connect(IoBridge.java:122) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452) at java.net.Socket.connect(Socket.java:884) at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124) at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:193) ... 15 more Caused by: android.system.ErrnoException: isConnected failed: EHOSTUNREACH (No route to host) at libcore.io.IoBridge.isConnected(IoBridge.java:223) ... 22 more 04-29 02:04:09.003 15719-15719/hivemind.com.ladies I/System.out: Resulted Value: 04-29 02:04:09.053 15719-15719/hivemind.com.ladies D/ViewRootImpl: #1 mView = android.widget.LinearLayout{29e5577 V.E...... ......I. 0,0-0,0} 04-29 02:04:09.133 15719-15719/hivemind.com.ladies D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1 04-29 02:04:09.143 15719-15719/hivemind.com.ladies W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView) 04-29 02:04:12.553 15719-15719/hivemind.com.ladies D/ViewRootImpl: #3 mView = null

Thorvald
  • 3,424
  • 6
  • 40
  • 66
  • 1
    This is a networking problem, not java or android. **EHOSTUNREACH (No Route to Host)** means when the TCP connection was attempted, the connection failed because the underlying protocol software could not find a network node to network node route to the designated target node – Masoom Badi May 04 '18 at 20:29
  • @Sam I was told that I need to re-configure the httpd.conf file in the EasyPhp folder in order to give my device access to the IP address but I have no idea how, I tried something but it didn't work – Thorvald May 04 '18 at 22:13
  • May i know which local server you are using like WAMP or XXAMP? – Masoom Badi May 05 '18 at 05:40
  • @Sam I am using WAMP – Thorvald May 05 '18 at 06:47
  • 1
    Yes you need to configure that file, if it is no route is found.. here is the way to do it. https://stackoverflow.com/questions/24005828/how-to-enable-local-network-users-to-access-my-wamp-sites – Masoom Badi May 05 '18 at 07:12
  • 1
    Make sure you run that link of yours /ladies_api/register.php in your browser and it is accessible from your browser. – Masoom Badi May 05 '18 at 07:13

0 Answers0