本文来自:http://stackoverflow.com/questions/21739276/android-volley-gives-me-400-error

本人是根据文中的其中一方法:

I had the same problem and i removed from the header:

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

now it works great!

以下是全文

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:

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:

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

Still getting the same error!

asked Feb 12 '14 at 20:50
Loolooii

2,577104171
 
    
are you sure you're putting in the auth headers correctly? if you're using basic auth you should be base64 encoding the username:password I believe – panini Feb 12 '14 at 20:54
    
@panini I'm already setting the base64 code as "somecodehere". – Loolooii Feb 12 '14 at 21:16
    
@Loolooii I have the same problem, did you find a solution ? – Robby Smet May 19 '14 at 11:36
    
@just8laze I'm just using Android's AsyncTask. It's much simpler and it works perfect. See this thread: stackoverflow.com/questions/9671546/asynctask-android-exampl‌​e – Loolooii May 19 '14 at 11:53
    
@Loolooii Yeah, I already have it working with AsyncTask and HttpPost. No idea why it doesn't work with Volley. Thanks for the response. – Robby Smet May 19 '14 at 11:56

9 Answers

I had the same problem and i removed from the header:

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

now it works great!

answered Nov 7 '15 at 15:02
 
user3136364

 
 
    
ahmagad this worked. – Bolling Oct 6 at 14:05

400 indicates a bad request, maybe you're missing Content-Type=application/json on your headers

answered Feb 12 '14 at 20:58
 
1  
it's something else, JsonRequest has that by default – thepoosh Feb 12 '14 at 21:03
    
I think @thepoosh is right, anyway I tried it and still getting the same error. – Loolooii Feb 12 '14 at 21:16
    
it's a server error, check the API – thepoosh Feb 12 '14 at 21:17
    
@thepoosh its not a server error, its a bad request which means if anything its a client error – panini Feb 12 '14 at 21:20
    
I meant to say, server initiated error, meaning the API was misused – thepoosh Feb 12 '14 at 21:23

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

  1. go to src/com/android/volley/toolbox/BasicNetwork.java
  2. Change the following lines
 if (statusCode < 200 || statusCode > 299) {
throw new IOException();
}

with

 if (statusCode < 200 || statusCode > 405) {
throw new IOException();
}

Hope this helps.

answered Apr 17 '15 at 8:47
stackex

1,5751312
 

I have removed this params.put("Content-Type", "application/x-www-form-urlencoded");

This is my Code Change.

@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
if(!isLogout) {
params.put("username", username);
params.put("password", password);
params.put("grant_type", "password");
} else {
}
return params;
} @Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
if(isLogout) {
params.put("Authorization", "bearer "+LibraryDataModel.getToken());
}else {
// Removed this line
// params.put("Content-Type", "application/x-www-form-urlencoded");
}
return params;
}
answered Nov 18 '14 at 16:32
dhiku

1,0561328
 

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:

My answer is base on my experience and so take note:

1.) When using POST method use "StringRequest" instead of "JsonObjectRequest"

2.) inside getHeaders Override the value with an 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.

answered Jan 6 '15 at 9:31
neferpitou

6691917
 

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 question here in SO.

Short answer: Don't use Base64.encodeToString() but put the already encoded String there.

answered Dec 17 '15 at 16:33
Raul Pinto

822512
 

400 error is because Content-Type is set wrong. Please do the following.

  1. GetHeader function should be as

        @Override
    public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> param = new HashMap<String, String>(); return param;
    }
  2. Add this new override function.

        @Override
    public String getBodyContentType() {
    return "application/json";
    }
answered Mar 17 at 21:28
Kashi

361
 

There can be multiple reasons for this error. One ofcouse as said by others is, maybe you are missing or have improperly set 'Content-type' header. If you are properly implemented that, other 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 problem in GET requests through volley. You need to find another way around it. Thats all.

answered Apr 11 at 11:49
Rohit

115
 
1  
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review– silwar Apr 11 at 12:43
    
This answer worked for me. That is why I posted it here. – Rohit Apr 11 at 15:46

Check if you are using correct SDK

For Android Studio / IntelliJIDEA:

File -> Project Structure -> Project -> Project SDK
Modules -> Check each modules "Module SDK"

Preferably, you should use "Google API (x.x)" instead of An

Android Volley gives me 400 error的更多相关文章

  1. Android Volley彻底解决(三),定制自己Request

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/17612763 经过前面两篇文章的学习,我们已经掌握了Volley各种Request ...

  2. [Android]Volley的使用

    Volley是Google I/O 2013上提出来的为Android提供简单快速网络访问的项目.Volley特别适合数据量不大但是通信频繁的场景. 优势 相比其他网络载入类库,Volley 的优势官 ...

  3. [转] Android Volley完全解析(一),初识Volley的基本用法

    版权声明:本文出自郭霖的博客,转载必须注明出处.   目录(?)[-] Volley简介 下载Volley StringRequest的用法 JsonRequest的用法   转载请注明出处:http ...

  4. Android Volley入门到精通:定制自己的Request

    经过前面两篇文章的学习,我们已经掌握了Volley各种Request的使用方法,包括StringRequest.JsonRequest.ImageRequest等.其中StringRequest用于请 ...

  5. Android Volley入门到精通:使用Volley加载网络图片

    在上一篇文章中,我们了解了Volley到底是什么,以及它的基本用法.本篇文章中我们即将学习关于Volley更加高级的用法,如何你还没有看过我的上一篇文章的话,建议先去阅读Android Volley完 ...

  6. Android Volley入门到精通:初识Volley的基本用法

    1. Volley简介 我们平时在开发Android应用的时候不可避免地都需要用到网络技术,而多数情况下应用程序都会使用HTTP协议来发送和接收网络数据.Android系统中主要提供了两种方式来进行H ...

  7. Android Volley完全解析

    1. Volley简介 我们平时在开发Android应用的时候不可避免地都需要用到网络技术,而多数情况下应用程序都会使用HTTP协议来发送和接收网络数据.Android系统中主要提供了两种方式来进行H ...

  8. Android Volley和Gson实现网络数据加载

    Android Volley和Gson实现网络数据加载 先看接口 1 升级接口 http://s.meibeike.com/mcloud/ota/cloudService POST请求 参数列表如下 ...

  9. Android Volley源码分析

    今天来顺手分析一下谷歌的volley http通信框架.首先从github上 下载volley的源码, 然后新建你自己的工程以后 选择import module 然后选择volley. 最后还需要更改 ...

随机推荐

  1. uboot mmc烧写命令

    mmc write addr blk# cnt 这个命令的作用是将内存上的数据写入mmc中 参数: addr: 从内存读取的位置 blk: 写入到mmc中block位置,这个位置是mmc的0地址的偏移 ...

  2. 【python】3.x,string与bytes的区别(文本,二进制数据)

    Python 3对文本和二进制数据作了更为清晰的区分.文本总是Unicode,由str类型表示, 二进制数据则由bytes类型表示. 不能拼接字符串和字节包,也无法在字节包里搜索字符串(反之亦然),也 ...

  3. 第三方FMDB的简单使用

    1,导入第三方头文件 #import "FMDB.h" //定义全局变量 @implementation InputInformationViewController { UITe ...

  4. Session阻塞 读写锁引发的小问题

      引子     我们来看两个ajax方法,先后的问题,会有什么样的结果? Javascript: $(function () { //第一个 $.ajax({ type: "POST&qu ...

  5. 云计算 云服务 hadoop

    云:是一种虚拟化的技术,重在资源管理. 云服务是云计算的一种商业模式,有三个层次: Iaas:场外服务器,存储和网络硬件:节省了维护成本和办公场地,公司可以在任何时候利用这些硬件来运行其应用 Paas ...

  6. MySQL数据库7 - 汇总和分组数据

    一 汇总和分组数据 查询语句 ---> 结果集(多条数据) ---> 聚合函数  ----> 单行记录 1.常用的聚合函数: sum()         数字             ...

  7. 基于ReentrantLock的AQS的源码分析(独占、非中断、不超时部分)

    刚刚看完了并发实践这本书,算是理论具备了,看到了AQS的介绍,再看看源码,发现要想把并发理解透还是很难得,花了几个小时细分析了一下把可能出现的场景尽可能的往代码中去套,还是有些收获,但是真的很费脑,还 ...

  8. # mysql -u root -p -bash: mysql: command not found

    [root@jboss ~]# mysql -u root -p-bash: mysql: command not found 需要安装mysql # yum install mysql之后就行 了

  9. 安装ant问题

    1  设置path, 在windwos 7下要重启 2  重启后,cmd----ant -version  Unable to locate tools.jar. Expected to find i ...

  10. Ajax学习重点总结

    1.什么是AJAX AJAX=Asynchronous JavaScript and XML(异步的JavaScript和XML). AJAX是在不重新加载整个页面的情况下,后台与服务器交换数据并更新 ...