Jose Lopez
Jose Lopez

Reputation: 242

Android - Forming an URL object specifying a port number

I am coding a login form mechanism for an Android app. The login activity will connect to a database and verify that the user and password supplied by the end user do exist in the database.

I am doing it through calling a server-side method called "login". The end-point for the server is: example.us.es:3456/login/ (institutional url address).

The problem comes when trying to form this URL using the URL class supplied by java.net library. I am doing it this way, but there must be something wrong:

public static final String ENDPOINT_LOGIN = "example.us.es:3456/login/"
URL url = new URL(ENDPOINT_LOGIN);

I am not sure how to form this URL as it contains a port number. In the Android developer webpage they suggest forming the URL as so:

http://username:password@host:8080/directory/file?query#ref

But my url address is not even similar to that one.

After debugging my code the error I am getting is:

java.net.MalformedURLException: Protocol not found: example.us.es:3456/login/

Just in case it helps, the code at my Login activity looks like this:

package com.example.loginapp;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class LoginActivity extends Activity {

    EditText mUser;
    EditText mPassword;
    Button mLoginButton;
    public static final String TAG = LoginActivity.class.getSimpleName();
    public static final String ENDPOINT_LOGIN = "example.us.es:3456/login/"

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_macceso);
        mUser = (EditText) findViewById(R.id.et_user);
        mPassword = (EditText)findViewById(R.id.et_password);
        mLoginButton = (Button)findViewById(R.id.b_signIn);

        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FetchLoginInfo fetchLogin = new FetchLoginInfo();
                fetchLogin.execute();
            }
        });
    }

    private void tryLogin(String username, String password)
    {
        HttpURLConnection connection = null;
        OutputStreamWriter request = null;
        BufferedReader reader = null;

        URL url = null;
        String response = null;
        String parameters = "user="+username+"&password="+password;

        try
        {
            url = new URL(ENDPOINT_LOGIN);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");

            request = new OutputStreamWriter(connection.getOutputStream());
            request.write(parameters);
            request.flush();
            request.close();
            String line = "";
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            reader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            // Respuesta del servidor se almacena en "response".
            response = sb.toString();
            isr.close();
            reader.close();
        } catch(IOException e) {
            // Error
            Log.e(TAG, "Error ", e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(TAG, "Error closing stream", e);
                }
            }
        }
    }

    private class FetchLoginInfo extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            tryLogin(mUser.getText().toString(), mPassword.getText().toString());
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
        //Check returned code from server
            Intent i = new Intent(MAccesoActivity.this, MCentralActivity.class);
            startActivity(i);
            super.onPostExecute(aVoid);
        }
    }
}

I guess after correcting the URL address will still appear other errors in tryLogin method, so I attached it above just in case any one kind soul want to take a quick look at it in search of any big mistake.

So, how to construct the URL I've been given? Thanks.


UPDATE (1)

As Rodrigo Henriques kindly pointed out, I forgot to add the "http" scheme at the beginning of the URL. Though that solved the problem (java.net.MalformedURLException), now I am getting a new one:

java.net.ConnectException: failed to connect to example.us.es/xxx.xxx.xxx.xx (port 3456): connect failed: ECONNREFUSED (Connection refused)

Maybe someone could tell me how to get rid of it. (I am not the server administrator; should I contact her?)


UPDATE (2)

Eventually the error:

java.net.ConnectException: failed to connect to example.us.es/xxx.xxx.xxx.xx (port 3456): connect failed: ECONNREFUSED (Connection refused)

has disappeared after having contacted the administrator. All problems solved.

Upvotes: 0

Views: 3890

Answers (1)

Rodrigo Henriques
Rodrigo Henriques

Reputation: 1812

Looking at this exception message I noticed that you forgot to put the http protocol at the beginning of your URL.

Best regards.

Upvotes: 2

Related Questions