Error "FileNotFoundException" when sending parameters with HttpURLConnection

0

I have my ASP.NET Web Api service where I make a simple login, which I tried with Postman (from Google Chrome) and it returns the data correctly but in Android I get the error back:

  

java.io.FileNotFoundException

AsynTask:

private class AsyncLogin extends AsyncTask<String, String, LoginModel>
{
    HttpURLConnection conn;
    BufferedReader reader = null;
    URL url = null;
    @Override
    protected  LoginModel doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL("http://192.168.1.5:80/api/ventas/Login");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            //return "exception";
        }
        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection)url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;");
            conn.setRequestProperty( "charset", "utf-8");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // Append parameters to URL
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("User", params[0])
                    .appendQueryParameter("Pass", params[1]);
            String query = builder.build().getEncodedQuery();

            // Open connection for sending data
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
           // return "exception";
        }

        InputStream stream = null;
        try {
            stream = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null)
            {
                buffer.append(line + "");
            }

            String finalJson = buffer.toString();
            JSONObject object = new JSONObject(finalJson);

            if(object.has("Message"))
            {
                return null;
            }
            else
            {
                LoginModel objModel = new LoginModel();

                objModel.setIdEmpleado(object.getInt("IdEmpleado"));
                objModel.setNombres(object.getString("Nombres"));
                objModel.setUsuario(object.getString("Usuario"));
                objModel.setClave(object.getString("Clave"));

                return objModel;
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if(conn != null)
            {
                conn.disconnect();
            }

            try {
                if(reader != null){reader.close();}

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

        return  null;
    }

    @Override
    protected void onPostExecute( LoginModel loginModel) {
        super.onPostExecute(loginModel);

        if (loginModel != null)
        {

            datosUsuario.setNombre_usuario(loginModel.getUsuario());
            datosUsuario.setClave(loginModel.getClave());
            datosUsuario.setNombreCompleto(loginModel.getNombres());
            datosUsuario.setIdEmpleado(loginModel.getIdEmpleado());

            SharedPreferences 
                preferences 
                = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("username", datosUsuario.getNombre_usuario());
            editor.putString("clave", datosUsuario.getClave());
            editor.putString("nombres", datosUsuario.getNombreCompleto());
            editor.putInt("idempleado", datosUsuario.getIdEmpleado());
            editor.commit();
            openPrincipal();
        }
        else
        {
            Toast.makeText(ctx, "Datos incorrectos" ,Toast.LENGTH_SHORT).show();
        }
    }
}

Service:

[HttpPost]
public IHttpActionResult Login(String User, String Pass)
{
    try
    {
        SombraEntities contexto = new SombraEntities();

        if (String.IsNullOrEmpty(User) || String.IsNullOrEmpty(Pass))
        {
            var data = new
            {
                Message = "No llegaron los datos."
            };

            return Json(data);
        }

        Usuario objusuario = (from data in contexto.Usuario
                              where data.User == User && data.Password == User
                              select data).SingleOrDefault();

        if (objusuario != null)
        {
            Empleado objempleado = objusuario.Empleado.FirstOrDefault();

            var data = new
            {
                IdEmpleado = objempleado.IdEmpleado,
                Nombres = objempleado.Nombres + " " + objempleado.Apellidos,
                Usuario = objempleado.Usuario.User,
                Clave = objempleado.Usuario.Password
            };

            return Json(data);
        }
        else
        {
            var data = new
            {
                Message = "Datos de Login Incorrectos"
            };

            return Json(data);
        }
    }
    catch (Exception e)
    {
        throw;
    }
}

Error in Debugger:

    
asked by cristian gonzalez 10.03.2017 в 19:54
source

1 answer

0
  

on android returns the error java.io.fileNotFoundException

Do you have permission to allow internet connection ?:

<uses-permission android:name="android.permission.INTERNET" />

Ensure the resource is available:

link

You comment that you tested it with Postman, therefore considering that the resource is found, check if the properties you define for the connection are correct, check the initialization of the Asynctask, you should receive an array where the first element is the user and the second is the password (Ensure the parameter names are correct):

Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("User", params[0])
                        .appendQueryParameter("Pass", params[1]);
    
answered by 10.03.2017 в 21:05