首先,我应该说我在这里阅读了几个类似的故事,但没有一个解决了我收到400错误代码的问题。我想使用 Post 方法将一些登录信息发送到 android studio 3.3.1 和 volley 库中的服务器。我在 getBody 中将参数作为键值发送,并在 getBodyContentType() 中设置内容类型。服务器只获取 xxx-form-urlencoded 格式的参数。我使用邮递员作为代理来查看正在发送的内容...邮递员以原始格式而不是 xxx-form-urlencoded 格式接收参数,我认为这就是为什么服务器无法获取登录参数并且我收到 400 错误代码(BasicNetwork .performRequest: Unexpected response code 400)- btw 服务器是用 asp.net 和 IIS webserver 编写的。
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();
}
}
对于那些面临类似问题的人:在对 Volley 感到失望之后,我通过 实现了网络内容HttpUrlConnection
,并发现了问题所在:我以 json 对象格式发送参数,即 {key:value,...} 而服务器预期 key:value&key :value&... 所以返回到 Volley 并像上面那样制作参数字符串并在 中使用它getBody()
,解决了我的问题。:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句