Android - Forming an URL object specifying a port number

Jose Lopez

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.

Rodrigo Henriques

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

Best regards.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Remove port number from a url in java

Proper URL forming with Query String and Anchor Hashtag

Invalid URI: Invalid port specified in C# on specifying URL with port number in it like http://localhost:8080/jasperserver/rest

Android Emulator - Finding Port Number

Discovering Kubernetes Pod without specifying port number

Avoiding port number in Liferay's assets URL

Does forming a reference to an object constitute access?

Dynamically forming array of object using given List

Complete Regex to match url with port number

HTTPS url with port number not working on iOS

forward the domain and remove the port number from the URL

Validate URL with valid port number and query string

Android arrayadapter without specifying object

Port number getting stripped out of URL

Get URL and port number from view

Regex optionally match port number in url

Nginx remove port number :8080 in the url

Redirect traffic to a domain with a port number without showing the port number in the URL

Forming a JSON Arrays with Objects using a Python object

How can I make Logitech Media Server available without specifying a port number?

How to connect url with port number in java with Jsoup?

nmap or ping a url with embedded port number?

When specifying a custom key in object, it turns it into an number

Remove port number in image url?

Forming the smallest number

Redirect to a port number depending on the URL

Can I bypass number-limit while specifying the port for socket library in Python?

send mail using MailKit without specifying port number

Grouping a dynamic array object and forming a object required