我编写的代码是将我的android工作室连接到wamp服务器mysql。我尝试从mysql检索登录信息到android。然而,它一直显示我意外的响应代码400.我应该如何更改我的代码?
@Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences =
getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF,
false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
Intent intent = new Intent(LoginActivity.this,
PofileActivity.class);
startActivity(intent);
}
}
private void login(){
//Getting values from edit texts
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Config.LOGIN_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//If we are getting success from server
if(response.equalsIgnoreCase(Config.LOGIN_SUCCESS)){
//Creating a shared preference
SharedPreferences sharedPreferences =
LoginActivity.this.getSharedPreferences(Config.SHARED_PREF_NAME,
Context.MODE_PRIVATE);
//Creating editor to store values to shared
preferences
SharedPreferences.Editor editor =
sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF,
true);
editor.putString(Config.EMAIL_SHARED_PREF, email);
//Saving values to editor
editor.commit();
//Starting profile activity
Intent intent = new Intent(LoginActivity.this,
PofileActivity.class);
startActivity(intent);
}else{
//If the server response is not success
//Displaying an error message on toast
Toast.makeText(LoginActivity.this, "Invalid username
or password", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
//You can handle error here if you want
}
}){
@Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put("Content-Type", "application/json");
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PASSWORD, password);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
@Override
public void onClick(View v) {
//Calling the login function
login();
}
答案 0 :(得分:1)
这是使用排球库时的常见问题。在您提出请求时,您可能无法设置正确的标头,这就是为什么它会给我们 400 Bad Request错误。
您可能需要覆盖 getBodyContentType()方法,以便正确更新Content-Type标头。
public String getBodyContentType()
{
return "application/xml";
}
我写了一篇博客来解释这个问题,以及如何解决这个问题。请参阅here以获取解决方案。