发送表单urlen codeD参数POST请求的Android凌空抽射 [英] Send form-urlencoded parameters in post request android volley
本文介绍了发送表单urlen codeD参数POST请求的Android凌空抽射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想打一个POST JSONObjectRequest与形式urlen codeD参数。我怎样才能做到这一点?我试过以下code,但无济于事。
I want to make a POST JSONObjectRequest with form urlencoded parameters. How can I do this? I've tried the following code, but to no avail.
final String api = "http://api.url";
final JSONObject jobj = new JSONObject();
jobj.put("Username", "usr");
jobj.put("Password", "passwd");
jobj.put("grant_type", "password");
final JsonObjectRequest jor = new JsonObjectRequest(Request.Method.POST, api, jobj, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();
//do other things with the received JSONObject
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
return pars;
}
};
//add to the request queue
requestqueue.AddToRequestQueue(jor);
我得到的API调用400错误的请求!我怎样才能解决这个问题?
I'm getting a 400 bad request with the api call! How can I fix it?
推荐答案
亚特很长很长的斗争,找到了解决办法。你需要重写getBodyContentType(),并返回应用程序/ x-WWW的形式urlen codeD;字符集= UTF-8;
Ater a long long struggle, found the solution. You need to override getBodyContentType() and return "application/x-www-form-urlencoded; charset=UTF-8";
StringRequest jsonObjRequest = new StringRequest(Request.Method.POST,
getResources().getString(R.string.base_url),
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
MyFunctions.toastShort(LoginActivity.this, response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley", "Error: " + error.getMessage());
error.printStackTrace();
MyFunctions.croutonAlert(LoginActivity.this,
MyFunctions.parseVolleyError(error));
loading.setVisibility(View.GONE);
}
}) {
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("username", etUname.getText().toString().trim());
params.put("password", etPass.getText().toString().trim());
return params;
}
};
AppController.getInstance().addToRequestQueue(jsonObjRequest);
这篇关于发送表单urlen codeD参数POST请求的Android凌空抽射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文