2017-06-05 79 views
0

我試圖在Android中發送POST數據。在互聯網上,我發現一些代碼與Apache,但代碼已棄用。在Android中發送POST數據

我需要波紋管發送值我的web服務,比上登記的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); 

如果有人知道如何做到這一點,可以與GSON與否。

回答

0

使用Retrofit與Gson。 添加這些庫與您的gradle這個

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' 

首先創建與改造實例

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; 
    } 
} 

一個單獨的類然後定義你的模型,我認爲是這樣的:

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 
    } 

} 

後那你已經準備好創建你對api的調用了。創建一個接口來定義你的API的方法。我假設你的post方法返回發佈的用戶。您將發送封裝在用戶模型中的所有數據,將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網站並閱讀教程。

+0

我需要在這裏放置什麼鏈接:public static final String BASE_URL =「http://yourApiBaseUrl.com/」; ? –

+0

而這一行我不明白:IUserService service = Api.getInstance()。create(IUserService.class); –

+0

想象一下,您的發佈方法網址是http://mywebapi.com/users,那麼您的基本網址是http://mywebapi.com/ 然後,在您的界面中,在發佈方法中,您應該編寫 @POST(「用戶「) 致電 postUser(@Body用戶用戶); 我更新了我的答案,第二個問題的正確答案是: UserService service = Api.getInstance()。create(IUserService.class); – fn5341