Problem with the 'ñ' in android

Question:

I am experiencing problems with a code snippet. The code that I attach below helps me to retrieve data from a webService, the results of said WebService can be verified here . The problem is that, on the test device (Samsung Galaxy Grand Prime – Android 5.1), the connection works and does what it should do, but on another device (Samsung A5 – Android 4.4) it generates the following exception:

08-23 09:41:23.584 28063-28107/com.example.luis.appgestionbsi W/System.err: java.io.FileNotFoundException: http://efibus.somee.com/ServiciosGestionBSI.asmx/SpinnerEmpresa?usuario=luisRonquillo&contraseña=bsi2017
08-23 09:41:23.584 28063-28107/com.example.luis.appgestionbsi W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
08-23 09:41:23.584 28063-28107/com.example.luis.appgestionbsi W/System.err:     at com.example.luis.appgestionbsi.ActDepositos$JSONTaskSpinnerEmpresa.doInBackground(ActDepositos.java:352)
08-23 09:41:23.584 28063-28107/com.example.luis.appgestionbsi W/System.err:     at com.example.luis.appgestionbsi.ActDepositos$JSONTaskSpinnerEmpresa.doInBackground(ActDepositos.java:333)
08-23 09:41:23.584 28063-28107/com.example.luis.appgestionbsi W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-23 09:41:23.584 28063-28107/com.example.luis.appgestionbsi W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-23 09:41:23.584 28063-28107/com.example.luis.appgestionbsi W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-23 09:41:23.584 28063-28107/com.example.luis.appgestionbsi W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-23 09:41:23.584 28063-28107/com.example.luis.appgestionbsi W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-23 09:41:23.584 28063-28107/com.example.luis.appgestionbsi W/System.err:     at java.lang.Thread.run(Thread.java:841)

This is the class: (the class obtains the JSON and saves it in 2 lists, one saves the IDs and the other the company name, and later the list of names is passed to a Spinner)

public class JSONTaskSpinnerEmpresa extends AsyncTask<String, String, String> {
        ProgressDialog dialog;
        public JSONTaskSpinnerEmpresa(ActDepositos actividad){
            dialog = new ProgressDialog(actividad);
        }
        @Override
        protected void onPreExecute(){
            dialog.setMessage("Cargando datos, espere.");
            dialog.show();
        }
        @Override
        protected String doInBackground(String... Parametros) {

            HttpURLConnection conexion = null;
            BufferedReader reader = null;
            try {
                URL url = new URL(Parametros[0]);
                conexion = (HttpURLConnection) url.openConnection();
                conexion.connect();
                InputStream stream = conexion.getInputStream();
                reader = new BufferedReader(new InputStreamReader(stream));
                StringBuffer buffer = new StringBuffer();

                // Lee línea por línea lo que se devuelve del WebService.
                String Line = "";
                while ((Line = reader.readLine()) != null) {
                    buffer.append(Line);
                }
                return buffer.toString(); // retorna Datos Manipulables en onPostExecute


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (conexion != null) {
                    conexion.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;

        }

        // Método una vez que lleguen los datos ...
        @Override
        protected void onPostExecute(String Resultado) {
            // se obtienen los datos del Resultado.
            super.onPostExecute(Resultado);
            try {
                ArrayList ListadoNombresEmpresas = new ArrayList();
                ListadoNombresEmpresas.add(0,"Seleccione...");
                final ArrayList ListadoidEmpresas = new ArrayList();
                ListadoidEmpresas.add(0,"0");
// esta parte recibe los datos del spinner y les da formato


                JSONArray ResultadosEnArray = new JSONArray(Resultado);
                for (int i = 1; i < ResultadosEnArray.length()+1; i++) {
                    JSONObject Objeto = ResultadosEnArray.getJSONObject(i-1);
                    Log.d("Salida ID:", Objeto.getString("idEmpresa"));
                    Log.d("Salida Nombre:", Objeto.getString("nombreEmpresa"));
                }
                for (int i = 1; i < ResultadosEnArray.length()+1; i++) {
                    JSONObject Objeto = ResultadosEnArray.getJSONObject(i-1);
                    ListadoNombresEmpresas.add(Objeto.getString("nombreEmpresa"));
                    ListadoidEmpresas.add(Objeto.getString("idEmpresa"));

                }//se agregan a dos arrays diferentes pero en mismo orden
                cmbEmpresa = (Spinner) findViewById(R.id.cmbEmpresaDepo);

                // Spinner adapter
                cmbEmpresa.setAdapter(new ArrayAdapter<String>(ActDepositos.this, android.R.layout.simple_spinner_dropdown_item, ListadoNombresEmpresas));
                try{
                    for(int i=1;i<ResultadosEnArray.length()+1;i++){
                        JSONObject Objeto = ResultadosEnArray.getJSONObject(i-1);
                        String a=Objeto.getString("idEmpresa");
                        if(a.equals(lblIDEmpresa.getText().toString())){
                            cmbEmpresa.setSelection(i);
                        }
                    }
                }
                catch (Exception ex){
                    Log.d("Salida error",ex.toString());
                }
                //metodo de spiner selected
                cmbEmpresa.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
                        String id = (String) ListadoidEmpresas.get(position);
                        lblIDEmpresa.setVisibility(View.VISIBLE);
                        lblIDEmpresa.setText(id);//si cambias el spinner, se actualiza su ID en el txtidContratista
                        String strAccion = "SpinnerContratista";
                        String strURL = "http://efibus.somee.com/ServiciosGestionBSI.asmx/";
                        String UrlWebService2 = strURL + strAccion + "?usuario=luisRonquillo&contraseña=bsi2017&idEmpresa="+id;
                        new JSONTaskSpinnerContratistas(ActDepositos.this).execute(UrlWebService2).toString();
                        String strAccion2 = "SpinnerDatosBanc";
                        String strURL2 = "http://efibus.somee.com/ServiciosGestionBSI.asmx/";
                        String UrlWebService3 = strURL2 + strAccion2 + "?usuario=luisRonquillo&contraseña=bsi2017&idEmpresa="+id;
                        new JSONTaskSpinnerDatosBanc(ActDepositos.this).execute(UrlWebService3).toString();

                    }
                    @Override
                    public void onNothingSelected(AdapterView<?> adapterView) {
                    }
                });

            } catch (Throwable t) {
                Log.e("Falla", t.toString());
            }
            if(dialog.isShowing())dialog.dismiss();
        }


    }

Why does it work on the test device, but not on another device? I want to clarify that I tested on 4 different devices, and of the 4 only this one is causing me that problem. The specific error appears on this line:

InputStream stream = conexion.getInputStream();

EDIT

updating the code as follows:

conexion.setDoInput(true);
                InputStream stream = conexion.getInputStream();

It generates the following error:

08-23 10:07:24.032 17541-18110/com.example.luis.appgestionbsi E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
                                                                                java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                                    at android.os.AsyncTask$3.done(AsyncTask.java:299)
                                                                                    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
                                                                                    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
                                                                                    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
                                                                                    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                                                                                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                                                                                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                                                                                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                                                                                    at java.lang.Thread.run(Thread.java:856)
                                                                                 Caused by: java.lang.IllegalStateException: Already connected
                                                                                    at java.net.URLConnection.checkNotConnected(URLConnection.java:464)
                                                                                    at java.net.URLConnection.setDoInput(URLConnection.java:862)
                                                                                    at com.example.luis.appgestionbsi.ActDepositos$JSONTaskSpinnerEmpresa.doInBackground(ActDepositos.java:352)
                                                                                    at com.example.luis.appgestionbsi.ActDepositos$JSONTaskSpinnerEmpresa.doInBackground(ActDepositos.java:333)
                                                                                    at android.os.AsyncTask$2.call(AsyncTask.java:287)
                                                                                    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
                                                                                    at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
                                                                                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
                                                                                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
                                                                                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
                                                                                    at java.lang.Thread.run(Thread.java:856) 
08-23 10:07:25.414 17541-17541/com.example.luis.appgestionbsi E/WindowManager: Activity com.example.luis.appgestionbsi.ActDepositos has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@417b91d8 that was originally added here
                                                                               android.view.WindowLeaked: Activity com.example.luis.appgestionbsi.ActDepositos has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@417b91d8 that was originally added here
                                                                                   at android.view.ViewRootImpl.<init>(ViewRootImpl.java:401)
                                                                                   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
                                                                                   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
                                                                                   at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
                                                                                   at android.view.Window$LocalWindowManager.addView(Window.java:552)
                                                                                   at android.app.Dialog.show(Dialog.java:277)
                                                                                   at com.example.luis.appgestionbsi.ActDepositos$JSONTaskSpinnerEmpresa.onPreExecute(ActDepositos.java:341)
                                                                                   at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
                                                                                   at android.os.AsyncTask.execute(AsyncTask.java:534)
                                                                                   at com.example.luis.appgestionbsi.ActDepositos.onCreate(ActDepositos.java:74)
                                                                                   at android.app.Activity.performCreate(Activity.java:5047)
                                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
                                                                                   at android.app.ActivityThread.access$700(ActivityThread.java:134)
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                   at android.os.Looper.loop(Looper.java:137)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:4867)
                                                                                   at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
                                                                                   at dalvik.system.NativeStart.main(Native Method)

Answer:

The problem is in the letter ñ which is not recognized by the encoding. You have to encode the contraseña parameter with uft-8 so that it can know it as valid:

String strAccion = "SpinnerEmpresa";
        String strURL = "http://efibus.somee.com/ServiciosGestionBSI.asmx/";
        String RestoURL="";
        try {
            RestoURL=URLEncoder.encode("contraseña","utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String UrlWebService = strURL + strAccion +"?usuario=luisRonquillo&"+RestoURL ;
        new JSONTaskSpinnerEmpresa(ActDepositos.this).execute(UrlWebService+"=bsi2017").toString();
Scroll to Top