使用Volley发布数据的最简单方法是什么?

时间:2018-11-19 13:41:01

标签: java android android-volley

我正在尝试使用Volley将3个字符串发送到将其发送到localhost服务器的php脚本。到目前为止,我已经知道了;

RegisterRequest;

public class RegisterRequest extends StringRequest {

    private static final String REGISTER_REQUEST_URL = "http://192.168.*.*:80/phptesting/Register.php";
    private Map<String, String> params;
    public RegisterRequest(String username, String password,String isAdmin,
                           Response.Listener<String> listener,
                           Response.ErrorListener errListener){
        super(Method.POST, REGISTER_REQUEST_URL,listener,errListener);
        params = new HashMap<>();
        params.put("username",username);
        params.put("password",password);
        params.put("isAdmin",isAdmin+"");
    }

    public Map<String, String> getparams() {
        return params;
    }
}

这是CreateUser;

public class CreateUser extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_user);
        this.setTitle("Create User");
        final EditText username1 = findViewById(R.id.Createusername);
        final EditText password1 = findViewById(R.id.CreatePassword);
        final Switch isAdmin = findViewById(R.id.isadmin);
        final Button createuser = findViewById(R.id.createuserbtn);
        if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
            isAdmin.setVisibility(View.GONE);
        }
        createuser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String username = username1.getText().toString();
                final String password = password1.getText().toString();
                final String isadmin = isAdmin.getText().toString();
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("Response Value: ", response);
                            if (response.equals("success")){
                                Intent intent = new Intent(CreateUser.this, MainActivity.class);
                                CreateUser.this.startActivity(intent);
                            }else{
                                AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
                                builder.setMessage("Register Failed")
                                        .setNegativeButton("Retry",null)
                                        .create()
                                        .show();
                        }
                    }
                };Response.ErrorListener errorListener = new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), String.valueOf(error), Toast.LENGTH_SHORT).show();
                    }
                };
                RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener,errorListener);
                RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
                queue.add(registerRequest);
            }
        });

    }

现在,唯一的错误是未定义索引。那就是因为Volley不会将数据发送到php脚本。当向其发送数据时,php脚本可以正常工作,所以我的问题是这样;我必须对脚本进行哪些更改才能将3个字符串发送过来?

1 个答案:

答案 0 :(得分:2)

请不要混淆代码,否则您将无法正确处理事情。

因此,请再上一堂课并在您的活动中使用它。

看看我写的这个类,您可以在任何地方使用它来处理任何类型的数据请求。

public class SendData {

private Context context;
private String url;
private HashMap<String, String> data;

private OnDataSent onDataSent;

public void setOnDataSent(OnDataSent onDataSent) {
    this.onDataSent = onDataSent;
}

public SendData(Context context, String url, HashMap<String, String> data) {
    this.context = context;
    this.url = url;
    this.data = data;
}

public void send(){
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if(onDataSent != null){
                onDataSent.onSuccess(response);
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if(onDataSent != null){
                onDataSent.onFailed(error.toString());
            }
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> map = new HashMap<>();
            map.putAll(data);
            return map;
        }

    };
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, 0, 0));
    RequestQueue requestQueue =  Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);
}

public interface OnDataSent{
    void onSuccess(String response);
    void onFailed(String error);
}

}

,现在您可以在任何活动中轻松使用它。只需在构造函数中提供数据并使用接口以这种方式跟踪事件

HashMap<String, String> data = new HashMap<>();
    data.put("username", "");//define the value
    data.put("password", "");//define the value
    data.put("is_admin", "");//define the value

    SendData sendData = new SendData(this, "", data); //defie the context and url properly
    sendData.setOnDataSent(new SendData.OnDataSent() {
        @Override
        public void onSuccess(String response) {
            //parse the response 
        }

        @Override
        public void onFailed(String error) {
            //something went wrong check the error
        }
    });
    sendData.send();

希望有帮助

快乐的编码

如果发生某些问题,请谅解:)