2017-06-05 11 views
0

AndroidでPOSTデータを送信しようとしています。インターネット上で私はApacheでいくつかのコードを見つけましたが、コードは廃止されました。私は値を送信する必要がAndroidでPOSTデータを送信する

は、私のWebサービスに、誰かがそれを行う方法を知っている場合は、GSONかとすることができPostgreSQLの

edtName = (EditText) findViewById(R.id.edtName); 
edtEmail = (EditText) findViewById(R.id.edtEmail); 
edtLogin = (EditText) findViewById(R.id.edtLogin); 
edtPassword = (EditText) findViewById(R.id.edtPassword); 

に登録よりも怒鳴ります。

答えて

0

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サイトをご覧になり、チュートリアルをお読みください。

+0

ここに入れる必要があるリンク:public static final String BASE_URL = "http://yourApiBaseUrl.com/"; ? –

+0

そして、私はこの行を理解できませんでした:IUserService service = Api.getInstance()。create(IUserService.class); –

+0

あなたのポストメソッドのURLがhttp://mywebapi.com/usersであると想像してから、あなたのベースURLはhttp://mywebapi.com/ です。あなたのインターフェイスでは、投稿メソッドには @POST( "ユーザー) postUser(@Bodyユーザーユーザー); 私の回答を更新しました.2番目の質問の正しい行は次のとおりです。 UserService service = Api.getInstance()。create(IUserService.class); – fn5341

関連する問題