在Android

时间:2017-06-05 00:34:31

标签: android json apache postgresql gson

我尝试在Android中发送POST数据。在互联网上,我找到了一些Apache代码,但代码已被弃用。

我需要将下面的值发送到我的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。

1 个答案:

答案 0 :(得分: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网站并阅读教程。