簡體   English   中英

如何在 Android POST 方法中使用 Retrofit 和 body?

[英]How to use Retrofit in Android POST method along with body?

我有一個帶有請求參數的 url 是 JsonFormat,如 {"EmailAddress":"user@gmail.com","PassWord":"password"} 它是請求的參數。 當我在 POSTMAN 中使用時,它的 oky.but 當我用程序請求時,我得到了錯誤響應。 我試過直到像這樣請看這個片段。

public class LoginModel {



@SerializedName("EmailAddress")
public String userName;


@SerializedName("PassWord")
public String userPass;

}

@Override
public String toString() {

    Log.e("POSTLOGIN_MODEL" , userName+"||"+userPass);
    return "{" +
            "EmailAddress='" + userName + '\'' +
            ", PassWord='" + userPass + '\'' +
            '}';

}
}

之后我使用了接口。

public interface ApiService {

@FormUrlEncoded
@POST("/json/syncreply/AuthenticateUserRequest?")
Call<LoginResponse> LoginService(@Field("EmailAddress") String userName,          @Field("PassWord") String userPass, Callback<LoginResponse> callBack);

之后我習慣通過活動調用這個接口方法。

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(input_username.getText().toString() != null && input_password.getText().toString() != null
                     && !input_username.getText().toString().isEmpty() && !input_password.getText().toString().isEmpty()){
                LoginModel loginCredentials = new LoginModel();
                loginCredentials.userName = "test@gmail.com";
                loginCredentials.userPass = "password";
                String request = "{\"EmailAddress\":\"raj@gmail.com\"," +
                        "\"PassWord\":\"pass\"}";
                sendPost(loginCredentials);

            }else{
                Toast.makeText(getApplicationContext() , "Please enter valid Username and Password." , Toast.LENGTH_LONG).show();
            }
        }
    });

public void sendPost(LoginModel name) {
    Log.e("TAG","||"+name.userPass+"||"+name.userName);
   // mAPIService.savePost(name).enqueue(new Callback<LoginModel>() {
        Call<LoginResponse> call = mAPIService.LoginService(name.userName, name.userPass, new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {

                Log.e("TAG" , "RESPONSE"+"||"+response.body());
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {

                Log.e("TAG" , "FAILURE"+"||"+t.getMessage());

            }
        });

     }

提前致謝。任何答案都將適用。我的英語是請避免它。

嘿 Rajan 使用 Request body 傳遞 Json

String request = "{\"EmailAddress\":\"raj@gmail.com\"," + "\"PassWord\":\"pass\"}";
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),request);

@Headers("Content-Type: application/json; charset=utf-8")
@POST("/json/syncreply/AuthenticateUserRequest")
Call<ResponseBody> AuthenticateUserRequest(@Body RequestBody body);

aCall.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                     if (response.isSuccessful()) {
                         ResponseBody responseBody = response.body();
                     }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });

首先在您的其余客戶端界面端更改如下方法,而不是分別獲取電子郵件和密碼,只獲取一個 String 的 ArrayList :

@FormUrlEncoded
    @POST(WEBSERVICE_NAME)
    Call<ModelClass> methodName(
            @Field("parameters" + "[]") ArrayList<String> paramsArrayList            
        );

現在,使用這樣的 GSON 庫將模型類的數組列表轉換為 JSON 字符串,

private ArrayList<String> getModelClassArrayinString(ArrayList<ModelClass> arrayList) {
        ArrayList<String> arrayListString = new ArrayList<>();
        for (int i = 0; i < arrayList.size(); i++) {
            arrayListString.add(new Gson().toJson(arrayList.get(i)).toString());
        }

        return arrayListString;
    }

所以你的最終電話將是這樣的:

Call<LoginResponse> call = mAPIService.LoginService(getModelClassArrayinString(arrayListofModelClass), new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {

                Log.e("TAG" , "RESPONSE"+"||"+response.body());
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {

                Log.e("TAG" , "FAILURE"+"||"+t.getMessage());

            }
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM