我想通过改装2将字符串从app发送到服务器,并获取返回值。问题是什么? 但它不起作用。
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RatingApiService retrofitService=retrofit.create(RatingApiService.class);
Call<String> call = retrofitService.registration("saeed","ali");
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if(response!=null){
Log.i("upload","is success:" +response.body());
}else{
Log.i("upload","response is null");
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.i("upload","onFailure: "+t.getMessage());
}
});
接口:
public interface RatingApiService {
@FormUrlEncoded
@POST("android/add2/{email}{password}")
Call<String> registration(@Path("email") String email, @Path("password") String password);
}
答案 0 :(得分:0)
您需要在方法中添加@Body
注释,如下所示。
@POST("users/new")
Call<User> createUser(@Body User user);
@Body
的内容作为请求正文发送到服务器。
如果要向服务器发送电子邮件和密码,则应创建包含此类数据的对象,并使用@Body
注释中的对象。
答案 1 :(得分:0)
而不是使用参数来传递数据;把它放在一个req.body,然后发送它。通过这样做,您可以绕过URL字符串限制,并且代码更有条理。
public interface RatingApiService {
@Headers("Content-Type: application/json") //Must be set to application/json so req.body can be read.
@POST("android")
Call<String> registration(@Body UserRegistrationRequest body);
}
现在,你可能会问什么是&#34; UserRegistrationRequest&#34;类?这将是将作为JSON对象发送的对象类。我们通过以下方式定义:
public class UserRegistrationRequest {
final String email;
final String password;
UserRegistrationRequest(String email, String password){
this.email = email;
this.password = password;
}
}
然后是最后一步。这是将对象转换为JSON对象并将其发送到服务器的方法。
UserRegistrationRequest userRegistrationRequest = new UserRegistrationRequest(
RegisterNameFragment.sFirstName, RegisterNameFragment.sLastName, RegisterEmailFragment.sEmail,
RegisterPasswordFragment.sPassword, RegisterAgeFragment.sAge);
Call<Void> call = retrofit.insertUserRegistration(userRegistrationRequest);
call.enqueue(new Callback<UserRegistration>() {
@Override
public void onResponse(Call<UserRegistration> call, Response<UserRegistration> response) {
Log.d("blue", "Data is sent");
}
@Override
public void onFailure(Call<UserRegistration> call, Throwable t) {
Log.d("blue", "fail");
}
});