[英]Send object with volley
我怀疑这让我感到困惑,我正在使用android / nodejs / postgreSQL,并且能够将http请求发送到服务器并存储信息。
但是我这样做是在没有考虑好的实践的情况下进行的,那就是让模型与用户关联。
因此,基本上我从寄存器表单中获取数据,然后使用表单信息进行简单的params.put并发送包含键/值信息的数据。
但是,现在我想拥有一个用户模型,并传递经过params.put的用户模型并做同样的事情。
这是考虑好的做法吗?还是我应该忘记用户模型并执行类似的操作?
这是我目前正在做的事情:
public void register(View view) {
//get form data
final String username = usernameTxt.getText().toString();
String password = passwordTxt.getText().toString();
String email = emailTxt.getText().toString();
Log.d("email",String.valueOf(isValidEmail(email)));
if (!isValidEmail(email)) {
emailTxt.setError("Invalid Email");
}
//inicialize a map with pair key value
final Map<String, String> params = new HashMap<String, String>();
// Add form fields to the map
params.put("username", username);
params.put("email", email);
params.put("password", password);
/**
* Efetua um pedido ao servidor
*
* @param URl url do servidor a aceder
* @param JSONObject objeto json a ser retornado através do access point
*
*/
JsonObjectRequest request = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//TODO verificar o status code da resposta apenas deverá registar login caso seja 200
//verifica
Log.d("response",response.toString());
Intent i = new Intent(Register.this,Login.class);
i.putExtra("username",username);
startActivity(i);
finish();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
String body;
//get response body and parse with appropriate encoding
if(error.networkResponse.data!=null) {
String statusCode = String.valueOf(error.networkResponse.statusCode);
try {
body = new String(error.networkResponse.data,"UTF-8");
JSONObject jsonObj = new JSONObject(body);
Log.d("body",String.valueOf(jsonObj.get("message")));
showToast(String.valueOf(jsonObj.get("message")));
} catch (UnsupportedEncodingException e) {
showToast("You need to connect to the internet!");
} catch (JSONException e) {
Log.d("json:","problems decoding jsonObj");
}
}
//do stuff with the body...
}
});
request.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
步骤1:使模型类可解析/可序列化。
步骤2:在模型类中重写toString()。
步骤3: Map<String,JSONObject> params = new HashMap<>(); JSONObject object = null; try{ object = new JSONObject(classObject.toString()); }catch (Exception e){ } params.put("key", object); JSONObject objectParams = new JSONObject(params);
Map<String,JSONObject> params = new HashMap<>(); JSONObject object = null; try{ object = new JSONObject(classObject.toString()); }catch (Exception e){ } params.put("key", object); JSONObject objectParams = new JSONObject(params);
做完了!!!
希望对您有所帮助,请尝试在您的应用程序中实施
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String REGISTER_URL = "http://foo.com/UserRegistration/volleyRegister.php";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_EMAIL = "email";
private EditText editTextUsername;
private EditText editTextEmail;
private EditText editTextPassword;
private Button buttonRegister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextEmail= (EditText) findViewById(R.id.editTextEmail);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonRegister.setOnClickListener(this);
}
private void registerUser(){
final String username = editTextUsername.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,username);
params.put(KEY_PASSWORD,password);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
@Override
public void onClick(View v) {
if(v == buttonRegister){
registerUser();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.