Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post JSON using Retrofit 2 in android?

I am new to android and I dont know how to POST using retrofit

I have my own server which returns me data, I need to fetch that one

This is how URL body looks like enter image description here

I have to send "city name" taken by edittext and pass it inside "ms_data's" keyword, i.e keyword="India"

This is what I have tried so far...

Retrofit Builder class

public class RetrofitBuilder {

public static Retrofit retrofit;

public static final String BASE_URL = "my url";

public static Retrofit getApiData()
{

    if(retrofit==null)
    {
        retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
                   .addConverterFactory(GsonConverterFactory.create()).build();
    }
    return retrofit;
}
}

POJO class

public class MessageFromServer {

private String city_name;

public MessageFromServer(String city_name) {
            this.city_name = city_name;
}

public String getCity_name() {
    return city_name;
}

public void setCity_name(String city_name) {
    this.city_name = city_name;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    MessageFromServer that = (MessageFromServer) o;

    return city_name != null ? city_name.equals(that.city_name) : that.city_name == null;

}

@Override
public int hashCode() {
    return city_name != null ? city_name.hashCode() : 0;
}

@Override
public String toString() {
    return "MessageFromServer{" +
            "city_name='" + city_name + '\'' +
            '}';
}
}

RequestBean class

public class JsonRequestBean {

private  String userId;
private String sessionToken;
private String clientType;
private String msServiceType;
private String msService;
private  String searchedLoc = null;
private List<String> msdata = null;




public List<String> getMsdata() {
    return msdata;
}

public void setMsdata(List<String> msdata) {
    this.msdata = msdata;
}


public JsonRequestBean() {
}

public JsonRequestBean(String userId, String sessionToken, String 
clientType, String msServiceType, String msService, String 
serachedLoc) {
    this.userId = userId;
    this.sessionToken = sessionToken;
    this.clientType = clientType;
    this.msServiceType = msServiceType;
    this.msService = msService;
    this.searchedLoc = serachedLoc;
}

public String getUserId() {
    return userId;
}

public void setUserId(String userId) {
    this.userId = userId;
}

public String getSessionToken() {
    return sessionToken;
}

public void setSessionToken(String sessionToken) {
    this.sessionToken = sessionToken;
}

public String getClientType() {
    return clientType;
}

public void setClientType(String clientType) {
    this.clientType = clientType;
}

public String getMsServiceType() {
    return msServiceType;
}

public void setMsServiceType(String msServiceType) {
    this.msServiceType = msServiceType;
}

public String getMsService() {
    return msService;
}

public void setMsService(String msService) {
    this.msService = msService;
}

public String getSerachedLoc() {
    return searchedLoc;
}

public void setSerachedLoc(String serachedLoc) {
    this.searchedLoc = serachedLoc;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    JsonRequestBean that = (JsonRequestBean) o;

    if (userId != null ? !userId.equals(that.userId) : that.userId != 
null) return false;
    if (sessionToken != null ? !sessionToken.equals(that.sessionToken) 
: that.sessionToken != null)
        return false;
    if (clientType != null ? !clientType.equals(that.clientType) : 
that.clientType != null)
        return false;
    if (msServiceType != null ? 
!msServiceType.equals(that.msServiceType) : that.msServiceType != 
null)
        return false;
    if (msService != null ? !msService.equals(that.msService) : 
that.msService != null)
        return false;
    return searchedLoc != null ? searchedLoc.equals(that.searchedLoc) 
: that.searchedLoc == null;

}

@Override
public int hashCode() {
    int result = userId != null ? userId.hashCode() : 0;
    result = 31 * result + (sessionToken != null ? 
sessionToken.hashCode() : 0);
    result = 31 * result + (clientType != null ? clientType.hashCode() 
: 0);
    result = 31 * result + (msServiceType != null ? 
msServiceType.hashCode() : 0);
    result = 31 * result + (msService != null ? msService.hashCode() : 
0);
    result = 31 * result + (searchedLoc != null ? 
searchedLoc.hashCode() : 0);
    return result;
}

@Override
public String toString() {
    return "JsonRequestBean{" +
            "userId='" + userId + '\'' +
            ", sessionToken='" + sessionToken + '\'' +
            ", clientType='" + clientType + '\'' +
            ", msServiceType='" + msServiceType + '\'' +
            ", msService='" + msService + '\'' +
            ", serachedLoc=" + searchedLoc +
            '}';
}

private class Msdata {

    public String keyword;

    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }
}
}

ResponseBean class //to fetch and store so that i can use however i need

public class JsonResponseBean {

@SerializedName("city_name")
@Expose
public String cityName;
@SerializedName("id")
@Expose
public String id;


public JsonResponseBean(String cityName, String id) {
    this.cityName = cityName;
    this.id = id;
}

public void setCityName(String cityName) {
    this.cityName = cityName;
}

public String getCityName() {
    return cityName;
}

public String getId() {
    return id;
}

public JsonResponseBean() {
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    JsonResponseBean that = (JsonResponseBean) o;

    if (cityName != null ? !cityName.equals(that.cityName) : 
 that.cityName != null)
        return false;
    return id != null ? id.equals(that.id) : that.id == null;

}

@Override
public int hashCode() {
    int result = cityName != null ? cityName.hashCode() : 0;
    result = 31 * result + (id != null ? id.hashCode() : 0);
    return result;
}


@Override
public String toString() {
    return "JsonRequestBean{" +
            "cityName='" + cityName + '\'' +
            ", id='" + id + '\'' +
            '}';
}
}

//inner class, you can see the image // i generated this using jsonschema2pojo.org

 class errorCode
 {
    @SerializedName("data")
    @Expose
    public List<JsonResponseBean> data = null;
    @SerializedName("error_code")
    @Expose
    public String errorCode;
    @SerializedName("message")
    @Expose
    public String message;
    @SerializedName("status")
    @Expose
    public String status;

}

API Class

public interface APIRequest {

@Headers({"Content-Type: application/json","Accept: 
application/json"})
@POST("/lfs/city_name")
Call<JsonResponseBean> locData (@Body JsonRequestBean mRequest);
}

DisplayActivity where i get the actual data

// as soon as i open the activty, onfailure will be called

public class DisplayActivity extends AppCompatActivity {


public static TextView tvM,tvN;
private Button btnFetch;
private EditText etCity;
private static final String TAG = "DisplayActivity";
private static final String VALUE = "displaytest";

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

    init();

    Intent i = getIntent();
    String text = i.getStringExtra("HESRU");
    tvN.setText(text);
     String city_name = etCity.getText().toString();
    final List<String> cityList = new ArrayList<>() ;
     cityList.add(city_name);
    Log.d(TAG, "onCreate: city name-"+city_name);


    btnFetch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Retrofit retrofit = RetrofitBuilder.getApiData();
            APIRequest service = retrofit.create(APIRequest.class);

            JsonRequestBean jsonRequestBean = new JsonRequestBean();
            jsonRequestBean.setClientType("mobile");
            jsonRequestBean.setMsServiceType("search");
            jsonRequestBean.setMsService("locality");
            jsonRequestBean.setMsdata(cityList);

            Call<JsonResponseBean> responseBeanCall = 
service.locData(jsonRequestBean);
            responseBeanCall.enqueue(new Callback<JsonResponseBean>() 
{
                @Override
                public void onResponse(Call<JsonResponseBean> call, 
Response<JsonResponseBean> response) {
                    Log.d(TAG, "onResponse: 
"+response.isSuccessful());
                    Log.d(TAG, "onResponse:, responebody---
"+response.body());
                }

                @Override
                public void onFailure(Call<JsonResponseBean> call, 
Throwable t) {
                    Log.e(TAG, "onFailure: message"+t.getMessage() );
                    t.printStackTrace();
                    Toast.makeText(DisplayActivity.this, "something 
went wrong", Toast.LENGTH_SHORT).show();
                }
            });
        }
    });


}
public void init() {
    tvM = (TextView) findViewById(R.id.textViewMSG);
    tvN = (TextView) findViewById(R.id.txtViewName);
    btnFetch = (Button) findViewById(R.id.buttonfetch);
    etCity = (EditText) findViewById(R.id.etCity);
}

Please help to solve this, i found that I should use HttpUrlConnection, but I dont know how to do that.

like image 229
Suhas Avatar asked Jan 29 '23 15:01

Suhas


2 Answers

Follow these steps:

1.) Firstly create modal class (MyRequestClass) for your Post request from http://www.jsonschema2pojo.org/

2.) Also create modal (MyResponseClass) for your server response from same site.

3.) Set values you want to send to your server by creating object of MyRequestClass.

4.) Then hit api using this method in your interface:

@POST("/provider/filter")
Call<MyResponseClass> sendDataToServer(@Body MyRequestClass myModal);
like image 172
Vicky Kumar Avatar answered Feb 03 '23 06:02

Vicky Kumar


your response class is wrong. it should be :

Response{
private Data[] data;

public Data[] getData ()
{
    return data;
}

public void setData (Data[] data)
{
    this.data = data;
}

@Override
public String toString()
{
    return "ClassPojo [data = "+data+"]";
}

public class Data
{
    private String id;

private String city_name;

public String getId ()
{
    return id;
}

public void setId (String id)
{
    this.id = id;
}

public String getCity_name ()
{
    return city_name;
}

public void setCity_name (String city_name)
{
    this.city_name = city_name;
}

@Override
public String toString()
{
    return "ClassPojo [id = "+id+", city_name = "+city_name+"]";
}
}
}

retrofit call:

@POST("/lfs/city_name")
Call<Response> locData (@Body JsonRequestBean mRequest);
}

add value to keyword using setter method

like image 37
Chandan Bhandari Avatar answered Feb 03 '23 06:02

Chandan Bhandari