【问题标题】:Retrofit Post request改造后请求
【发布时间】:2019-01-04 20:37:33
【问题描述】:

我想将用户凭据发布到以下网址 :http://myurl/authenticate

参数:登录。类型 (JSON) 用户名:字符串 密码:字符串

"login":{"username": "JohnDoe","password": "eoDnhoJ" }

如果成功

{
" r e s u l t " : " S u c c e s s " ,
"response": "Users Session ID"
}

这是我的代码

public interface APIService {

    @POST("/authenticate")
    @FormUrlEncoded
    Call<Login> savePost(@Field("username") String username,
                         @Field("password") String password);
}

public class ApiUtils {

    private ApiUtils() {}

    public static final String BASE_URL = "http://myurl/";

    public static APIService getAPIService() {

        return RetrofitClient.getClient(BASE_URL).create(APIService.class);
    }
}

公共类登录{

@SerializedName("username")
@Expose
private String username;
@SerializedName("password")
@Expose
private String password;
//getters and setters
}

public class RetrofitClient {
    private static Retrofit retrofit = null;

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

public class LoginActivity extends AppCompatActivity {

    private EditText usernameEditText,passwordEditText;
    private Button button;
    private APIService mAPIService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        usernameEditText=(EditText)findViewById(R.id.username);
        passwordEditText=(EditText)findViewById(R.id.password);
        button=(Button)findViewById(R.id.signup);

        mAPIService = ApiUtils.getAPIService();


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String uname=usernameEditText.getText().toString();
                String pass=passwordEditText.getText().toString();
                if(TextUtils.isEmpty(uname)){
                    Toast.makeText(LoginActivity.this, "Username cannot be empty", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(TextUtils.isEmpty(pass)){
                    Toast.makeText(LoginActivity.this, "Password cannot be empty", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(pass.length()<4){
                    Toast.makeText(LoginActivity.this, "Password should be greater than four characters", Toast.LENGTH_SHORT).show();
                    return;
                }

                sendPost(uname, new StringBuilder(uname).reverse().toString());

            }
        });
    }


    public void sendPost(String username, String password) {
        mAPIService.savePost(username, password).enqueue(new Callback<Login>() {
            @Override
            public void onResponse(Call<Login> call, Response<Login> response) {

                if(response.isSuccessful()) {
                    showResponse(response.body().toString());
                    Log.i("Pritish", "post submitted to API." + response.body().toString());
                    Intent intent=new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<Login> call, Throwable t) {
                Log.e("Pritish", "Unable to submit post to API.");
            }
        });
    }

    public void showResponse(String response) {
        Log.i("Abbu",response);
    }
}

每当我提交用户名和密码时,我都会得到空值,有人可以帮助我吗?我如何获取 sessionId。我尝试寻找各种 egs,但我现在很困惑。

【问题讨论】:

  • 只是一个问题,你为什么在没有将密码传递给你的函数的情况下调用sendPost(uname, new StringBuilder(uname).reverse().toString());
  • 用户提交的密码我不关心,我只想提交用户名的反面。你可以忽略它。它并不重要

标签: android retrofit2


【解决方案1】:

而不是下面的代码

@POST("/authenticate")
@FormUrlEncoded
Call<Login> savePost(@Field("username") String username,
                     @Field("password") String password);

使用此代码

@POST("/authenticate")
Call<Login> savePost(@Query("username") String username,
                     @Query("password") String password);

【讨论】:

    【解决方案2】:

    第 1 步:代替这段代码

    public interface APIService {
    
        @POST("/authenticate")
        @FormUrlEncoded
        Call<Login> savePost(@Field("username") String username,
                             @Field("password") String password);
    }
    

    使用此代码:

    public interface APIService {
    
        @POST("/authenticate")
        Call<Login> savePost(@Body RequestBody body);
    }
    

    第 2 步:在 LoginActivity 中替换此代码

    public void sendPost(String username, String password) {
            mAPIService.savePost(username, password).enqueue(new Callback<Login>() {
                @Override
                public void onResponse(Call<Login> call, Response<Login> response) {
    
                    if(response.isSuccessful()) {
                        showResponse(response.body().toString());
                        Log.i("Pritish", "post submitted to API." + response.body().toString());
                        Intent intent=new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
    
                @Override
                public void onFailure(Call<Login> call, Throwable t) {
                    Log.e("Pritish", "Unable to submit post to API.");
                }
            });
        }
    

    改成这段代码:

    public void sendPost(String username, String password) {
    
    
            HashMap<String, String> params = new HashMap<>();
            params.put("username", username);
            params.put("password", password);      
            String strRequestBody = new Gson().toJson(params);
    
        //create requestbody
            final RequestBody requestBody = RequestBody.create(MediaType.
                    parse("application/json"),strRequestBody);
    
                mAPIService.savePost(requestBody).enqueue(new Callback<Login>() {
                    @Override
                    public void onResponse(Call<Login> call, Response<Login> response) {
    
                        if(response.isSuccessful()) {
                            showResponse(response.body().toString());
                            Log.i("Pritish", "post submitted to API." + response.body().toString());
                            Intent intent=new Intent(getApplicationContext(), MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }
    
                    @Override
                    public void onFailure(Call<Login> call, Throwable t) {
                        Log.e("Pritish", "Unable to submit post to API.");
                    }
                });
            }
    

    【讨论】:

      【解决方案3】:

      通过以下方式替换您的登录类

       @SerializedName("result")
          @Expose
          private String rESULT;
          @SerializedName("response")
          @Expose
          private String response;
      
          public String getRESULT() {
              return rESULT;
          }
      
          public void setRESULT(String rESULT) {
              this.rESULT = rESULT;
          }
      
          public String getResponse() {
              return response;
          }
      
          public void setResponse(String response) {
              this.response = response;
          }
      

      【讨论】:

        【解决方案4】:
        1. 添加 ServiceGenerator 类:

          public class ServiceGenerator {
          
          private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
          
          private static Retrofit.Builder builder =
                  new Retrofit.Builder()
                          .baseUrl(BASEURL)
                          .addConverterFactory(ScalarsConverterFactory.create());
          
          public static <S> S createService(Class<S> serviceClass) {
              Retrofit retrofit = builder.client(httpClient.build()).build();
              return retrofit.create(serviceClass);
          }
          public static Retrofit getRetrofit()
          {
              return builder.client(httpClient.build()).build();
          }
          

          }

        2.添加接口RetrofitAPI:

         public interface RetrofitApi {
                    @POST("/api/v1/user")
                    Call<ResponseBody> login(@Body RequestBody loginBody);
            }
        

        3.在管理器类中添加登录方法:

        public void retrofitLogin(JSONObject login, final String tag) {
                RetrofitApi service = ServiceGenerator.createService(RetrofitApi.class);
                Call<ResponseBody> result = service.login(convertJsonToRequestBody(login));
                result.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                        retrofitCheckResponse(response, tag);
                    }
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        if (t instanceof IOException) {
                            Log.e("retrofit error", "retrofit error");
                            sendErrorRetrofit(mContext.getString(R.string.ERROR), 500, tag);
                        }
                    }
                });
            }
        

        将 JSONObject 转换为 RequestBody 的方法:

         private RequestBody convertJsonToRequestBody(JSONObject jsonObject) {
                    if (jsonObject != null) {
        
                        return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
                    } else {
                        return null;
                    }
                }
        

        4.现在调用你的 retrofitLogin 方法:

        JSONObject mLoginParams = new JSONObject();
        JSONObject mLoginObj = new JSONObject();
        mLoginParams.put("username", uname);   
        mLoginParams.put("password", pass);
        mLoginObj.put("appType","mobile");
        mLoginObj.put("user", mLoginParams);
        volleyRequest.retrofitLogin(mLoginObj, "Login");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-10
          • 2021-08-05
          • 2018-11-13
          • 1970-01-01
          • 2018-02-16
          • 2022-10-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多