gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:34:21 25 4
gpt4 key购买 nike

我是 android 的新手,我不知道如何使用 retrofit 进行 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

//一旦我打开activty,就会调用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,但我不知道该怎么做。

最佳答案

请按照以下步骤操作:

1.) 首先为来自 http://www.jsonschema2pojo.org/ 的 Post 请求创建模态类 (MyRequestClass)

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

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

4.) 然后在您的界面中使用此方法访问 api:

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

关于android - 如何在 android 中使用 Retrofit 2 发布 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46154156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com