Saltar al contenido

Enviar solicitud de publicación con parámetros usando Retrofit

Basta ya de investigar en otras páginas ya que estás al espacio justo, contamos con la respuesta que necesitas encontrar sin liarte.

Solución:

build.gradle

      compile 'com.google.code.gson:gson:2.6.2'

      compile 'com.squareup.retrofit2:retrofit:2.1.0'// compulsory

      compile 'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion

Inicio de sesión APi Ponga dos parámetros

    
        "UserId": "1234",
        "Password":"1234"
    

Respuesta de inicio de sesión

    
        "UserId": "1234",
        "FirstName": "Keshav",
        "LastName": "Gera",
        "ProfilePicture": "312.113.221.1/GEOMVCAPI/Files/1.500534651736E12p.jpg"
    

APIClient.java

    import retrofit2.Retrofit;
    import retrofit2.converter.gson.GsonConverterFactory;

    class APIClient 

        public static final String BASE_URL = "Your Base Url ";
        private static Retrofit retrofit = null;

        public static Retrofit getClient() 
            if (retrofit == null) 
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            
            return retrofit;
        
    

Interfaz APIInterface

    interface APIInterface 

        @POST("LoginController/Login")
        Call createUser(@Body LoginResponse login);
    

Iniciar sesión Pojo

    package pojos;

    import com.google.gson.annotations.SerializedName;

    public class LoginResponse 


        @SerializedName("UserId")
        public String UserId;
        @SerializedName("FirstName")
        public String FirstName;
        @SerializedName("LastName")
        public String LastName;
        @SerializedName("ProfilePicture")
        public String ProfilePicture;
        @SerializedName("Password")
        public String Password;
        @SerializedName("ResponseCode")
        public String ResponseCode;
        @SerializedName("ResponseMessage")
        public String ResponseMessage;

        public LoginResponse(String UserId, String Password) 
            this.UserId = UserId;
            this.Password = Password;
        

        public String getUserId() 
            return UserId;
        

        public String getFirstName() 
            return FirstName;
        

        public String getLastName() 
            return LastName;
        

        public String getProfilePicture() 
            return ProfilePicture;
        

        public String getResponseCode() 
            return ResponseCode;
        

        public String getResponseMessage() 
            return ResponseMessage;
        
    

Actividad principal

    package com.keshav.retrofitloginexampleworkingkeshav;

    import android.app.Dialog;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    import pojos.LoginResponse;
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    import utilites.CommonMethod;

    public class MainActivity extends AppCompatActivity 

        TextView responseText;
        APIInterface apiInterface;

        Button loginSub;
        EditText et_Email;
        EditText et_Pass;
        private Dialog mDialog;
        String userId;
        String password;

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

            apiInterface = APIClient.getClient().create(APIInterface.class);

            loginSub = (Button) findViewById(R.id.loginSub);
            et_Email = (EditText) findViewById(R.id.edtEmail);
            et_Pass = (EditText) findViewById(R.id.edtPass);

            loginSub.setOnClickListener(new View.OnClickListener() 
                @Override
                public void onClick(View v) 
                    if (checkValidation()) 
                        if (CommonMethod.isNetworkAvailable(MainActivity.this))
                            loginRetrofit2Api(userId, password);
                        else
                            CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);
                    
                
            );
        

        private void loginRetrofit2Api(String userId, String password) 
            final LoginResponse login = new LoginResponse(userId, password);
            Call call1 = apiInterface.createUser(login);
            call1.enqueue(new Callback() 
                @Override
                public void onResponse(Call call, Response response) 
                    LoginResponse loginResponse = response.body();

                    Log.e("keshav", "loginResponse 1 --> " + loginResponse);
                    if (loginResponse != null) 
                        Log.e("keshav", "getUserId          -->  " + loginResponse.getUserId());
                        Log.e("keshav", "getFirstName       -->  " + loginResponse.getFirstName());
                        Log.e("keshav", "getLastName        -->  " + loginResponse.getLastName());
                        Log.e("keshav", "getProfilePicture  -->  " + loginResponse.getProfilePicture());

                        String responseCode = loginResponse.getResponseCode();
                        Log.e("keshav", "getResponseCode  -->  " + loginResponse.getResponseCode());
                        Log.e("keshav", "getResponseMessage  -->  " + loginResponse.getResponseMessage());
                        if (responseCode != null && responseCode.equals("404")) 
                            Toast.makeText(MainActivity.this, "Invalid Login Details n Please try again", Toast.LENGTH_SHORT).show();
                         else 
                            Toast.makeText(MainActivity.this, "Welcome " + loginResponse.getFirstName(), Toast.LENGTH_SHORT).show();
                        
                    
                

                @Override
                public void onFailure(Call call, Throwable t) 
                    Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
                    call.cancel();
                
            );
        

        public boolean checkValidation() 
            userId = et_Email.getText().toString();
            password = et_Pass.getText().toString();

            Log.e("Keshav", "userId is -> " + userId);
            Log.e("Keshav", "password is -> " + password);

            if (et_Email.getText().toString().trim().equals("")) 
                CommonMethod.showAlert("UserId Cannot be left blank", MainActivity.this);
                return false;
             else if (et_Pass.getText().toString().trim().equals("")) 
                CommonMethod.showAlert("password Cannot be left blank", MainActivity.this);
                return false;
            
            return true;
        
    

CommonMethod.java

    public class CommonMethod 


        public static final String DISPLAY_MESSAGE_ACTION =
                "com.codecube.broking.gcm";

        public static final String EXTRA_MESSAGE = "message";

        public  static boolean isNetworkAvailable(Context ctx) 
            ConnectivityManager connectivityManager
                    = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        

        public static void showAlert(String message, Activity context) 

            final AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(message).setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() 
                        public void onClick(DialogInterface dialog, int id) 

                        
                    );
            try 
                builder.show();
             catch (Exception e) 
                e.printStackTrace();
            

        
    

activity_main.xml

    

            

            

            

                

            

            

                

            

            

                

Esta es una solución simple en la que no necesitamos usar JSON

public interface RegisterAPI 
@FormUrlEncoded
@POST("/RetrofitExample/insert.php")
public void insertUser(
        @Field("name") String name,
        @Field("username") String username,
        @Field("password") String password,
        @Field("email") String email,
        Callback callback);

método para enviar datos

private void insertUser()
    //Here we will handle the http request to insert user to mysql db
    //Creating a RestAdapter
    RestAdapter adapter = new RestAdapter.Builder()
            .setEndpoint(ROOT_URL) //Setting the Root URL
            .build(); //Finally building the adapter

    //Creating object for our interface
    RegisterAPI api = adapter.create(RegisterAPI.class);

    //Defining the method insertuser of our interface
    api.insertUser(

            //Passing the values by getting it from editTexts
            editTextName.getText().toString(),
            editTextUsername.getText().toString(),
            editTextPassword.getText().toString(),
            editTextEmail.getText().toString(),

            //Creating an anonymous callback
            new Callback() 
                @Override
                public void success(Response result, Response response) 
                    //On success we will read the server's output using bufferedreader
                    //Creating a bufferedreader object
                    BufferedReader reader = null;

                    //An string to store output from the server
                    String output = "";

                    try 
                        //Initializing buffered reader
                        reader = new BufferedReader(new InputStreamReader(result.getBody().in()));

                        //Reading the output in the string
                        output = reader.readLine();
                     catch (IOException e) 
                        e.printStackTrace();
                    

                    //Displaying the output as a toast
                    Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show();
                

                @Override
                public void failure(RetrofitError error) 
                    //If any error occured displaying the error as toast
                    Toast.makeText(MainActivity.this, error.toString(),Toast.LENGTH_LONG).show();
                
            
    );

Ahora podemos obtener la solicitud de publicación usando php aur cualquier otro script del lado del servidor.

Tutorial de actualización de Android de origen

He encontrado la solución. El problema era un problema en la estructura de mis clases. Así que los actualicé como los siguientes ejemplos.

public class LandingPageReport 

    private ArrayList GetDetailWithMonthWithCodeResult;

    // + Getter Setter methods


public class LandingPageReportItem 

    private String code;

    private String field1;

    // + Getter Setter methods

Y luego uso esta configuración de actualización

@POST("/GetDetailWithMonthWithCode")
void getLandingPageReport(@Field("code") String code,
                          @Field("monthact") String monthact,
                          Callback cb);

valoraciones y comentarios

Recuerda que puedes compartir este escrito si te fue de ayuda.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *