gpt4 book ai didi

Android Volley 给我 400 错误

转载 作者:IT老高 更新时间:2023-10-28 23:04:26 31 4
gpt4 key购买 nike

我正在尝试向我的 API 发出 POST 请求,它在 Postman 中工作(我得到一个有效的 JSON 对象),但不使用 Volley 。使用以下代码:

String URL = "http://somename/token";
RequestQueue queue = Volley.newRequestQueue(StartActivity.this);
queue.add(new JsonObjectRequest(Method.POST, URL, null,
new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// handle response
Log.i("StartActivity", response.toString());
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// handle error
Log.i("StartActivity", error.toString());
}
}) {

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("username", "someUsername");
headers.put("password", "somePassword");
headers.put("Authorization", "Basic someCodeHere");
return headers;
}
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("grant_type", "client_credentials");

return params;
}
});

我收到以下错误:

02-12 21:42:54.774: E/Volley(19215): [46574] BasicNetwork.performRequest: Unexpected response code 400 for http://somename/token/

我看过很多例子,但我真的不明白这里出了什么问题。有人知道吗?

我用这个方法更新了代码:

HashMap<String, String> createBasicAuthHeader(String username, String password) {
HashMap<String, String> headerMap = new HashMap<String, String>();

String credentials = username + ":" + password;
String base64EncodedCredentials =
Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headerMap.put("Authorization", "Basic " + base64EncodedCredentials);

return headerMap;
}

并将 getHeaders() 更改为:

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return createBasicAuthHeader("username", "password");
}

还是出现同样的错误!

最佳答案

我遇到了同样的问题,我从标题中删除了:

  headers.put("Content-Type", "application/json");

现在效果很好!

关于Android Volley 给我 400 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21739276/

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