Модифицированный метод POST с помощью служб WCF, получающих код ошибки 400: неверный запрос - PullRequest
0 голосов
/ 25 мая 2018

Я хочу вызвать метод POST (REST API) в Retrofit с данными JSON.Библиотека почтальона и залпа работает хорошо, я хочу реализовать ее в Retrofit ..

Я смотрю в нее в течение последних двух дней, но не могу найти решение .. Я сослался на эту ссылку и эта ссылка и многое другое, которое выглядит похоже, но не работает для меня .. Может быть, я делаю что-то не так ..

Это мои входные данные enter image description here и выходные данные выглядят так enter image description here, и моя часть кодирования лежит здесь

public class Api {
private static Retrofit retrofit = null;
public static ApiInterface getClient() {


    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl("xxxx/Service1.svc/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    //Creating object for our interface
        ApiInterface api = retrofit.create(ApiInterface.class);
    return api; // return the APIInterface object
}}

и интерфейс как

public interface ApiInterface {

@FormUrlEncoded
@POST("UserLogin")
Call<SignUpResponse> registration(@Field("Mobile_no") String mobile,
                                  @Field("Password") String pass,
                                  @Field("RegID") String regId);}

и обновленный класс Pojo как

public class SignUpResponse {


@SerializedName("UserLoginResult")
@Expose
private UserLoginResult userLoginResult;

public UserLoginResult getUserLoginResult() {
    return userLoginResult;
}

public void setUserLoginResult(UserLoginResult userLoginResult) {
    this.userLoginResult = userLoginResult;
}}class UserLoginResult {

@SerializedName("Email_id")
@Expose
private String emailId;
@SerializedName("First_name")
@Expose
private String firstName;
@SerializedName("Last_name")
@Expose
private String lastName;
@SerializedName("Message")
@Expose
private String message;
@SerializedName("Mobile_no")
@Expose
private String mobileNo;
@SerializedName("Password")
@Expose
private String password;
@SerializedName("RegID")
@Expose
private String regID;
@SerializedName("Status")
@Expose
private String status;

public String getEmailId() {
    return emailId;
}

public void setEmailId(String emailId) {
    this.emailId = emailId;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public String getMobileNo() {
    return mobileNo;
}

public void setMobileNo(String mobileNo) {
    this.mobileNo = mobileNo;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getRegID() {
    return regID;
}

public void setRegID(String regID) {
    this.regID = regID;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}}

и по MainActivity

Api.getClient().registration("xxxNumberhere","rd","222").enqueue(new Callback<SignUpResponse>() {
        @Override
        public void onResponse(Call<SignUpResponse> call, Response<SignUpResponse> response) {
            signUpResponsesData = response.body();
            Toast.makeText(getApplicationContext(), response.body().getUserLoginResult().getMessage(), Toast.LENGTH_SHORT).show();
            progressDialog.dismiss();

        }

        @Override
        public void onFailure(Call<SignUpResponse> call, Throwable t) {
            Log.d("response", t.getStackTrace().toString());
            progressDialog.dismiss();

        }
    });

и мои зависимости

compile 'com.squareup.retrofit2:retrofit:2.1.0'
// JSON Parsing
compile 'com.google.code.gson:gson:2.6.1'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

Заранее спасибо ..

Ответы [ 2 ]

0 голосов
/ 25 мая 2018

Спасибо за вашу любезную помощь @Subin Babu

Изменения, которые я сделал в своем проекте

1) Добавлен класс POJO с тем же именем, что и у параметра

public class User {

public String getMobile_no() {
    return Mobile_no;
}

public void setMobile_no(String mobile_no) {
    Mobile_no = mobile_no;
}

public String getPassword() {
    return Password;
}

public void setPassword(String password) {
    Password = password;
}

public String getRegID() {
    return RegID;
}

public void setRegID(String regID) {
    RegID = regID;
}

private String Mobile_no;
private String Password;
private String RegID;

public User(String Mobile_no,String Password,String RegID)
{
    this.Mobile_no = Mobile_no;
    this.Password = Password;
    this.RegID = RegID;
}}

2) Обновлен класс ApiInterface как

public interface ApiInterface {

@POST("UserLogin")
Call<SignUpResponse> registration(@Body User body);
}

3) Обновлен класс MainActivity как

User user = new User("xxxNumber", "rd", "555");

    Api.getClient().registration(user).enqueue(new Callback<SignUpResponse>() {
        @Override
        public void onResponse(Call<SignUpResponse> call, Response<SignUpResponse> response) {
            signUpResponsesData = response.body();
        }

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

        }
    });

4) Все остальные остаются неизменными ..

0 голосов
/ 25 мая 2018

Следующие имя класса и функции относятся к моему проекту

Вы можете сделать это,

public interface APIService {
    @POST("seq/restapi/checkpassword")
    @Headers({
        "Content-Type: application/json;charset=utf-8",
        "Accept: application/json;charset=utf-8",
        "Cache-Control: max-age=640000"
    })
    Call<Post> savePost(@Body User user);
}

Затем вы можете отправить данные как,

 User user = new User(); 
 user.setUsername("abcd"); 
 user.setPassword("password"); 
 public void sendPost(User user) { 
    mAPIService.savePost(user).enqueue(new Callback<Post>() { 
        @Override public void onResponse(Call<Post> call, Response<Post> response) { 
            if (response.isSuccessful()) { } 
            } 
        @Override public void onFailure(Call<Post> call, Throwable t) { }

    });
 } 

Вы можете проанализировать error 400,

Gson gson = new GsonBuilder().create(); 
RetrofitError mError = gson.fromJson(response.errorBody().string(), RetrofitError.class); 
Toast.makeText(context, mError.getMessages().getError().get(0).getMessage(),Toast.LENGTH_LONG).show(); 

и добавить класс RetrofitError,

public class RetrofitError {
    @SerializedName("messages")
    @Expose
    private Messages messages;

    public Messages getMessages() {
        return messages;
    }

    public void setMessages(Messages messages) {
        this.messages = messages;
    }
}

Если у вас есть какие-либо сомнения, обратитесь к мой вопрос .Удачного кодирования ... Не стесняйтесь спрашивать, если таковые имеются.Примечание: добавьте POJO

    public class Example {

@SerializedName("UserLoginResult")
@Expose
private UserLoginResult userLoginResult;

public UserLoginResult getUserLoginResult() {
return userLoginResult;
}

public void setUserLoginResult(UserLoginResult userLoginResult) {
this.userLoginResult = userLoginResult;
}

}

-------- UserLoginResult import com.google.gson.annotations.Expose;import com.google.gson.annotations.SerializedName;

public class UserLoginResult {

@SerializedName("Email_id")
@Expose
private String emailId;
@SerializedName("First_name")
@Expose
private String firstName;
@SerializedName("Last_name")
@Expose
private String lastName;
@SerializedName("Message")
@Expose
private String message;
@SerializedName("Mobile_no")
@Expose
private String mobileNo;
@SerializedName("Password")
@Expose
private String password;
@SerializedName("RegID")
@Expose
private String regID;
@SerializedName("Status")
@Expose
private String status;

public String getEmailId() {
return emailId;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public String getMobileNo() {
return mobileNo;
}

public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getRegID() {
return regID;
}

public void setRegID(String regID) {
this.regID = regID;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...