我正在创建一个注册应用程序,除了一个问题之外,几乎所有的工作都是如此。 好的,现在我将告诉你代码。那有点长。
public interface SupportopApi {
@POST("/api/registration")
Call<ResponseBody> registration (@Body SupportopObj supportopObj);}
这是界面。 现在我将向您展示由JsonPoJo解析的模型。
public class SupportopObj {
@SerializedName("username")
@Expose
private String username;
@SerializedName("password")
@Expose
private String password;
@SerializedName("email")
@Expose
private String email;
@SerializedName("firstName")
@Expose
private String firstName;
@SerializedName("lastName")
@Expose
private String lastName;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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;
}}
好的那是模型,我是碎片,所以这里是MainActivity
public class MainActivity extends AppCompatActivity {
FrameLayout cont;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ApiClient.initializeInstance("https://supportop.eu-gb.mybluemix.net/");
cont = findViewById(R.id.container);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new FragmentActivity()).commit();
}}
这是改装课程,我在那里初始化了改造。
public class ApiClient {
private static ApiClient instance;
private SupportopApi supportopApi;
private ApiClient(String endpoint) {
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS);
clientBuilder.addInterceptor(chain -> {
Request request = chain.request();
request = request.newBuilder()
.addHeader("Content-Type", "application/json")
.build();
return chain.proceed(request);
});
supportopApi = new Retrofit.Builder()
.baseUrl(endpoint)
.client(clientBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(SupportopApi.class);
}
public static synchronized void initializeInstance(String endpoint) {
if (instance == null) {
instance = new ApiClient(endpoint);
}
}
public static synchronized ApiClient getInstance() {
if (instance == null) {
throw new IllegalStateException("PentairAPIClient has not been initialized.");
}
return instance;
}
public Call<ResponseBody> registration(SupportopObj supportopObj) {
return supportopApi.registration(supportopObj);
}
}}
这是主要的片段类。
public class FragmentRegistration extends Fragment {
View mainView;
EditText username, email, password, name;
Button button;
ApiClient pentairAPIClient = ApiClient.getInstance();
SupportopObj supportopObj = new SupportopObj();
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mainView = getLayoutInflater().inflate(R.layout.registration, container, false);
username = mainView.findViewById(R.id.username);
email = mainView.findViewById(R.id.email);
password = mainView.findViewById(R.id.password);
name = mainView.findViewById(R.id.name);
button = mainView.findViewById(R.id.register);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
supportopObj.setUsername(username.getText().toString());
supportopObj.setEmail(email.getText().toString());
supportopObj.setPassword(password.getText().toString());
updateApp();
}
});
return mainView;
}
public void updateApp() {
FragmentRegistration context = this;
Call<ResponseBody> call = pentairAPIClient.registration(supportopObj);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
Toast.makeText(getContext(), String.valueOf(response.body()),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "Error...", Toast.LENGTH_SHORT).show();
}
});
}
}}
好的,让我解释一下我的问题是什么。当我点击注册时,我必须从response.body
获得一条消息,其中注册成功完成。首先,我尝试将呼叫注册无效,如此Call<Void> registration
,但这会返回response.body
null。
现在,当我在呼叫机构Call<ResponseBody> registration
时,他会回复OkHttp3:{ResponseBody$1@830038646440}
这样的事情。
当我在体内进行调试时,有一个内容,看起来像这样
content = {Buffer@830038501160} "[text="Registration Successfully completed"]"
这是图像。我该如何解决这个问题,我希望成功完成文本注册。
答案 0 :(得分:0)
试试这段代码
使用body()方法从api获取响应并转换为字符串
“body()”是成功响应的反序列化响应主体 string类似于“toString()”
public interface RetrofitService{
@GET("/api/registration")
Call<ResponseBody> registration(paramshere);//function to call api
}
RetrofitService service = retrofit.create(RetrofitService.class);
Call<ResponseBody> result = service.registration(params);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());//convert reponse to string
Snackbar snackbar = Snackbar
.make( cont , "Registered successfully",Snackbar.LENGTH_LONG);//pass your activity view as first param
snackbar.show();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
答案 1 :(得分:0)
将response.body转换为jsonArray:
JSONArray jsonArray = new JSONArray(response.body());
String responseText = jsonArray.getJSONObject(i).getString("text");
您将“注册成功完成”作为responseText。