gpt4 book ai didi

android - 在发布请求android volley中发送form-urlencoded参数

转载 作者:IT老高 更新时间:2023-10-28 21:36:34 25 4
gpt4 key购买 nike

我想用表单 urlencoded 参数创建一个 POST JSONObjectRequest。我怎样才能做到这一点?我尝试了以下代码,但无济于事。

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 错误请求!我该如何解决?

最佳答案

经过长期的斗争,找到了解决方案。您需要覆盖 getBodyContentType() 并返回 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);

关于android - 在发布请求android volley中发送form-urlencoded参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25998529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com