RetrofitとGsonを使用してください。
public class User {
@SerializedName("Name")
private String name;
@SerializedName("Email")
private String email;
@SerializedName("Login")
private String login;
@SerializedName("Password")
private String password;
public User(...){
//Constructor
}
}
後: はまず
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
あなたのGradleにこれらのライブラリを追加します。その後、あなたのモデルを定義改造インスタンスと
public class Api {
public static final String BASE_URL = "http://yourApiBaseUrl.com/";
private static Retrofit retrofit = null;
public static Retrofit getInstance(){
if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
をシングルトンクラスを作成し、私はこのような何かをされたと仮定しますそれで、あなたはapiへの呼び出しを作成する準備が整いました。インターフェイスを作成して、APIのメソッドを定義します。私はあなたの投稿メソッドが投稿されたユーザーを返すと仮定します。あなたは、HTTP要求の本体内に、ユーザモデルにカプセル化されたすべてのデータを送信します:
public interface UserService {
@POST("yourPostUrl")
Call<User> postUser(@Body User user);
}
は、今ではPOSTを行うための時間です。次のように、投稿を実行する方法を作成します。
private void postUser(String edtName, String edtEmail, String edtLogin, String edtPassword){
UserService service = Api.getInstance().create(UserService.class);
Call<User> userCall = service.postUser(new User(edtName, edtEmail, edtLogin, edtPassword));
userCall.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});
}
それだけで、役立ちます。
詳細については、retrofitのWebサイトをご覧になり、チュートリアルをお読みください。
ここに入れる必要があるリンク:public static final String BASE_URL = "http://yourApiBaseUrl.com/"; ? –
そして、私はこの行を理解できませんでした:IUserService service = Api.getInstance()。create(IUserService.class); –
あなたのポストメソッドのURLがhttp://mywebapi.com/usersであると想像してから、あなたのベースURLはhttp://mywebapi.com/ です。あなたのインターフェイスでは、投稿メソッドには @POST( "ユーザー) postUser(@Bodyユーザーユーザー); 私の回答を更新しました.2番目の質問の正しい行は次のとおりです。 UserService service = Api.getInstance()。create(IUserService.class); –
fn5341