Android Volley 给了我 400 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21739276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android Volley gives me 400 error
提问by Loolooii
I'm trying to make a POST
request to my API and it works in Postman
(I get a valid JSON object), but not using Volley
. With the following code:
我正在尝试向POST
我的 API 发出请求并且它在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;
}
});
I get the following error:
我收到以下错误:
02-12 21:42:54.774: E/Volley(19215): [46574] BasicNetwork.performRequest: Unexpected response code 400 for http://somename/token/
I have seen a lot of examples and I don't really see what is going wrong here. Anyone any idea?
我看过很多例子,但我真的不明白这里出了什么问题。有人知道吗?
I updated the code with this method:
我用这个方法更新了代码:
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;
}
and changed getHeaders()
to:
并改为getHeaders()
:
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return createBasicAuthHeader("username", "password");
}
Still getting the same error!
仍然得到同样的错误!
回答by Loolooii
I had the same problem and i removed from the header:
我遇到了同样的问题,我从标题中删除了:
headers.put("Content-Type", "application/json");
now it works great!
现在效果很好!
回答by Priyanshu Singh
If you are passing the json value to in body(raw json).No need to set the content type as headers.put("Content-Type", "application/json; charset=utf-8");
如果您将 json 值传递给 in body(raw json)。无需将内容类型设置为 headers.put("Content-Type", "application/json; charset=utf-8");
When I was using the content type in header callback ,the 400 response status I was getting in logcat.I commented headers.put("Content-Type", "application/json; charset=utf-8"); as because I am passing raw json in body while calling api.screenshot for postman is attached.It will help
当我在标头回调中使用内容类型时,我在 logcat 中获得了 400 响应状态。我评论了 headers.put("Content-Type", "application/json; charset=utf-8"); 因为我在调用 api.screenshot for postman 时在 body 中传递原始 json。它会有所帮助
private void volleyCall(String email, String password) {
RequestQueue queue= Volley.newRequestQueue(this);
String URL = "http://XXXX.in:8080/XXXX/api/userService/login";
Map<String, String> jsonParams = new HashMap<S[enter image description here][1]tring, String>();
jsonParams.put("email", email);
jsonParams.put("password", password);
Log.d(TAG,"Json:"+ new JSONObject(jsonParams));
JsonObjectRequest postRequest = new JsonObjectRequest( Request.Method.POST, URL,new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG,"Json"+ response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle Error
Log.d(TAG, "Error: " + error
+ "\nStatus Code " + error.networkResponse.statusCode
+ "\nResponse Data " + error.networkResponse.data
+ "\nCause " + error.getCause()
+ "\nmessage" + error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String,String>();
// headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
@Override
public String getBodyContentType() {
return "application/json";
}
};
queue.add(postRequest);
}
LogCat:
LoginActivity: Json:{"email":"[email protected]","password":"abcde"}
LoginActivity: Error: com.android.volley.ServerError
Status Code 400
Response Data [B@63ca992
Cause null
messagenull
回答by Kashi
400 error is because Content-Type is set wrong. Please do the following.
400 错误是因为 Content-Type 设置错误。请执行以下操作。
GetHeader function should be as
@Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> param = new HashMap<String, String>(); return param; }
Add this new override function.
@Override public String getBodyContentType() { return "application/json"; }
GetHeader 函数应该是
@Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> param = new HashMap<String, String>(); return param; }
添加这个新的覆盖功能。
@Override public String getBodyContentType() { return "application/json"; }
回答by Rohit
There can be multiple reasons for this error.
此错误可能有多种原因。
One reason, of course, as said by others, is that maybe you are missing or have improperly set 'Content-type' header.
当然,正如其他人所说,原因之一是您可能缺少或不正确地设置了“内容类型”标头。
If you have properly implemented that, another possible reason is that you are sending params directly from your URL. There may be a case when params is a string with some white spaces in it. These white spaces cause problems in GET requests through Volley. You need to find another way around it. That's all.
如果您正确地实现了这一点,另一个可能的原因是您直接从您的 URL 发送参数。可能存在 params 是包含一些空格的字符串的情况。这些空格会导致通过 Volley 的 GET 请求出现问题。你需要找到另一种方法来解决它。就这样。
回答by Leonardo Pinto
400 indicates a bad request, maybe you're missing Content-Type=application/json
on your headers
400 表示一个错误的请求,也许你Content-Type=application/json
的标题丢失了
回答by neferpitou
I have the same issue before and I got the solution in my project:
我以前遇到过同样的问题,我在我的项目中得到了解决方案:
RequestQueue requestManager = Volley.newRequestQueue(this);
String requestURL = "http://www.mywebsite.org";
Listener<String> jsonListerner = new Response.Listener<String>() {
@Override
public void onResponse(String list) {
}
};
ErrorListener errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.w("Volley Error", error.getMessage());
}
};
StringRequest fileRequest = new StringRequest(Request.Method.POST, requestURL, jsonListerner,errorListener){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("token", account.getToken());
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
// do not add anything here
return headers;
}
};
requestManager.add(fileRequest);
In the code Snippet above I used Post Method:
在上面的代码片段中,我使用了 Post 方法:
My answer is base on my experience and so take note:
我的回答是基于我的经验,所以请注意:
1.) When using POST method use "StringRequest" instead of "JsonObjectRequest"
1.) 当使用 POST 方法时使用“StringRequest”而不是“JsonObjectRequest”
2.) inside getHeaders Override the value with an Empty HashMap
2.) 在 getHeaders 里面用一个 Empty HashMap 覆盖这个值
example snippet:
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("token", account.getToken());
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
// do not add anything here
return headers;
}
And everything works in my case.
在我的情况下一切正常。
回答by stackex
I've got this error and now Iit's been fixed. I did what is told in this link. What you need to do is
我遇到了这个错误,现在已经修复了。我做了这个链接中所说的。你需要做的是
- go to src/com/android/volley/toolbox/BasicNetwork.java
- Change the following lines
- 去 src/com/android/volley/toolbox/BasicNetwork.java
- 更改以下几行
if (statusCode < 200 || statusCode > 299) {
throw new IOException();
}
with
和
if (statusCode < 200 || statusCode > 405) {
throw new IOException();
}
Hope this helps.
希望这可以帮助。
回答by Raul Pinto
In Android 2.3 there is a problem using Base64.encodeToString() as it introduces a new line in HTTP header. See my response to this questionhere in SO.
在 Android 2.3 中,使用 Base64.encodeToString() 会出现问题,因为它在 HTTP 标头中引入了一个新行。在 SO 中查看我对这个问题的回答。
Short answer: Don't use Base64.encodeToString() but put the already encoded String there.
简短回答:不要使用 Base64.encodeToString() 而是将已经编码的字符串放在那里。
回答by suresh prajapati
I have find a solution if you are using postman for hitting the api and your api have defined serializer field like skill = serializers.JSONField() then that type of error occurred-
如果您使用邮递员来访问 api 并且您的 api 已经定义了序列化器字段,如 Skill = serializers.JSONField() ,那么我找到了一个解决方案,然后发生了这种类型的错误 -
Solution For POSTMAN-you just add binary=True inside JSONField ex- skill = serializers.JSONField(binary=True)
邮递员的解决方案-您只需在 JSONField 中添加 binary=True ex- Skill = serializers.JSONField(binary=True)
Solution for Android or other client then- you just remove binary=True inside JSONField ex- skill = serializers.JSONField()
Android 或其他客户端的解决方案 - 您只需删除 JSONField 中的 binary=True ex- Skill = serializers.JSONField()
回答by Dhruv Tyagi
Somertimes this error 400 is arise due to Request type so you need to change the Request.Method.GET
to Request.Method.POST
and than it works like a charm.
有时这个错误 400 是由于请求类型而出现的,所以你需要改变它Request.Method.GET
,Request.Method.POST
然后它就像一个魅力。