0
我想使用body x-www-form-urlencoded參數向其餘api發出POST請求。我已經嘗試了下面的代碼,但我得到錯誤代碼400. 我一直在試圖從幾小時調試,但獲得相同的響應。任何幫助將不勝感激。Android Volley意外的響應代碼400與身體x-www-form-urlencoded
public class LoginFragment extends Fragment {
private static final String TAG = "LoginFragment";
EditText mUsername, mPassword;
Button mLogin;
String url = "abc";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_login, container, false);
mUsername = (EditText) rootView.findViewById(R.id.login_name_edit_text);
mPassword = (EditText) rootView.findViewById(R.id.login_password_edit_text);
mLogin = (Button) rootView.findViewById(R.id.login_button);
mLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String username = mUsername.toString();
String password = mPassword.toString();
if (username.trim().length() > 0 && password.trim().length() > 0) {
checkLogin(username, password);
} else {
Toast.makeText(getContext(), "Please enter the credentials!", Toast.LENGTH_SHORT).show();
}
}
});
return rootView;
}
private void checkLogin(final String username, final String password) {
// Tag used to cancel the request
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Launch main activity
Intent intent = new Intent(getActivity(),
MainActivity.class);
startActivity(intent);
getActivity().finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("message");
Toast.makeText(getContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
};
// Adding request to request queue
MySingleton.getInstance(getContext()).addToRequestQueue(strReq);
}
}
在https://pastebin.com/5k9WaU6E試試我的示例代碼。看起來像你有類似的問題http://stackoverflow.com/questions/42827279/basicnetwork-performrequest-unexpected-response-code-400-post#comment72767244_42827279,注意評論 – BNK
仍然會出現相同的錯誤 –