如何在android中使用Retrofit 2发布JSON?

时间:2017-09-11 11:02:47

标签: android json http-post retrofit2

我是Android的新手,我不知道如何使用改造进行POST

我有自己的服务器,它返回数据,我需要获取那个

这是URL正文的样子 enter image description here

我必须发送edittext采用的“城市名称”并将其传递到“ms_data”关键字内,即keyword =“India”

这是我到目前为止所尝试的......

Retrofit Builder类

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课程

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类

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类 //获取和存储,以便我可以使用但是我需要

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 + '\'' +
            '}';
}
}

//内部类,你可以看到图像 //我使用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类

public interface APIRequest {

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

DisplayActivity我获取实际数据

//一旦打开活动,就会调用onfailure

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);
}

请帮助解决这个问题,我发现我应该使用HttpUrlConnection,但我不知道该怎么做。

3 个答案:

答案 0 :(得分:4)

请按照以下步骤操作:

1。)首先从http://www.jsonschema2pojo.org/

为你的帖子请求创建模态类(MyRequestClass)

2。)同时为来自同一站点的服务器响应创建模态(MyResponseClass)。

3.。)通过创建MyRequestClass的对象来设置要发送到服务器的值。

4.)然后在界面中使用此方法点击api:

@POST("/provider/filter")
Call<MyResponseClass> sendDataToServer(@Body MyRequestClass myModal);

答案 1 :(得分:1)

你的回复课是错误的。 它应该是:

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+"]";
}
}
}

改装电话:

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

使用setter方法

为关键字添加值

答案 2 :(得分:0)

  

删除/。来自POST方法,因为改造基础URL以/结尾。所以你的网址   现在是baseurl // lfs / city_name

    @POST("lfs/city_name")<----- change
Call<JsonResponseBean> locData (@Body JsonRequestBean mRequest);
  

添加标题以供请求

  public class RetrofitClient {

    private static final String TAG = "RetrofitClient";

    public static Retrofit getClient() {
        Retrofit retrofit = null;
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);



        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(logging);
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();

                // Request customization: add request headers
                Request.Builder requestBuilder = original.newBuilder()
                        .header("Licence", BuildConfig.Licence); // <-- this is the important line

                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });

        if (retrofit==null) {
            Log.d(TAG, "getClient: base url  "+ BuildConfig.base_url);
            retrofit = new Retrofit.Builder()
                    .baseUrl(BuildConfig.base_url)
                    .client(httpClient.build())

                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

    public static Retrofit getClientWithAdminBaseUrl() {
         Retrofit retrofit = null;
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

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