首先,我应该说我在这里阅读了几个类似的故事,但是没有一个解决了我收到400个错误代码的问题。 我想使用Post方法将一些登录信息发送到android studio 3.3.1和凌空库中的服务器。我在getBody中将参数作为键值发送,并在getBodyContentType()中设置内容类型。 服务器仅以xxx-形式-urlencoded格式获取参数。我使用邮递员作为代理,以查看发送的内容... 邮递员以Body格式接收原始参数,而不是以xxx形式的urlencoded格式接收原始参数,我认为这就是服务器无法获取登录参数并且收到400错误代码的原因(BasicNetwork.performRequest:意外的响应代码400)- btw服务器是用asp.net和IIS网络服务器编写的。
private void PostParams()
{
Boolean is_valid_user;
try {
String URL = "http://192.168.43.22:5555/AOBServices/login";
JSONObject jsonBody = new JSONObject();
jsonBody.put("my_very_special_key","Love");
jsonBody.put("username", "amir");
jsonBody.put("password", "1234");
jsonBody.put("grant_type", "password");
final String requestBody = jsonBody.toString();
final StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
Toast.makeText(LoginActivity.this, "SUCCESSSSSSSSSSSSS \n response: "+response, Toast.LENGTH_SHORT).show();
//update shared prefs.....
myResponse=response;
shprefs= new sharedPrefsClass(getApplicationContext());
shprefs.setDefaults("USER_ID", mEmail);
shprefs.setDefaults("IS_SIGNEDIN", true);
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// As of f605da3 the following should work
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
}
}
}
}) {
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
@Override
protected String getParamsEncoding() {
return "utf-8";
}
@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
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
对于面临类似问题的人:
在对Volley感到失望之后,我通过HttpUrlConnection
实现了网络功能,并发现了问题所在:
我以json对象格式(即{key:value,...})发送参数,而服务器期望key:value&key:value&...
因此返回到Volley并像上面一样制作参数字符串并在getBody()
中使用它解决了我的问题。 :)