在我的应用程序中,根据客户需求,我必须发送一个字符串参数作为字符串响应,而作为响应,我将从服务器获取另一个字符串。我正在使用volley库进行String post请求。但是在我的onResponse(字符串响应)方法中,打印响应只给出了200.我已经检查了POSTMAN上的Post请求,在那里可以看到来自服务器端的String响应。我将在下面发布我的代码。我有什么地方出错吗?需要你的帮助。
try {
RequestQueue requestQueue = Volley.newRequestQueue(myContext);
JSONObject jsonBody = new JSONObject();
jsonBody.put("EmailID", "acacva@gmail.com");
jsonBody.put("PassWord", "agaha");
jsonBody.put("IsMobile", "true");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, apiClass.API_LOGIN, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("afaga", response);
Toast.makeText(myContext,response,Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
@Override
public String getBodyContentType() {
return "text/plain; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody .getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
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
Log.d("statuscode",responseString);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
OnResponse()内的响应变量只返回200,POSTMAN将响应显示为字符串,例如:“hhdhbdwdbdhhddhbdb”。
答案 0 :(得分:3)
在 parseNetworkResponse(NetworkResponse response) 方法中,首先解析 200 的状态代码,并将值传递给成功方法调用 Response.success(...),从而在Toast消息中获取 200 状态代码。
您应该拨打 super.parseNetworkResponse(响应) ,而不是 Response.success(..) 下方。
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
//TODO if you want to use the status code for any other purpose like to handle 401, 403, 404
String statusCode = String.valueOf(response.statusCode);
//Handling logic
return super.parseNetworkResponse(response);
}