当我在终端上运行时,此cURL命令正常工作:
curl -X POST -H“Content-Type:application / json”-H“授权: 基本uname:pass123“-d'{”userName“:”uname“,”password“:”pass123“}' “http://mysite123.com/api/Login”
现在,我正在尝试使用Android Volley发送此帖子请求。代码如下:
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url = "http://mysite123.com/api/Login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("userName", "uname");
params.put("password", "pass123");
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers=new HashMap<String,String>();
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
headers.put("Accept-Encoding", "utf-8");
String creds = String.format("%s:%s","uname","pass123");
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", auth );
return headers;
}
};
queue.add(stringRequest);
但它在stackTrace中给出了错误:
09-03 07:46:43.823 17712-17918 / com.ankitshubham97.gpsmonitoring E / Volley:[108117] BasicNetwork.performRequest:http://mysite123.com/api/Login的意外响应代码400 09-03 07:46:43.833 17712-17712 / com.ankitshubham97.gpsmonitoring E / Qmage:isQIO:stream不是QIO文件 09-03 07:46:43.843 17712-17712 / com.ankitshubham97.gpsmonitoring W / System.err:com.android.volley.ServerError 09-03 07:46:43.853 17712-17712 / com.ankitshubham97.gpsmonitoring W / System.err:at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:163) 09-03 07:46:43.853 17712-17712 / com.ankitshubham97.gpsmonitoring W / System.err:at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)<
可能是什么问题?或者从android直接发送curl命令的任何方法?
编辑:我甚至使用https://incarnate.github.io/curl-to-php/将上面的cURL命令转换为php代码,php也运行正常。我想知道Volley出了什么问题!
答案 0 :(得分:0)
使用邮递员帮助了我。因此,问题是'{"userName":"uname","password":"pass123"}'
将以json格式和正文(而不是param)作为原始表单发送。所以,我用这个方法:
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
@Override
public String getBodyContentType() {
return "application/json";
}
我之前将requestBody
定义为:
JSONObject jsonBody = new JSONObject();
try{
jsonBody.put("userName", "uname");
jsonBody.put("password", "pass123");
}
catch (JSONException e){
}
final String requestBody = jsonBody.toString();