在一个字符串登录请求登录中。在onResponse中,我返回的所有状态码都是200。我也想获取返回的数据。我不确定从现在开始该往哪里走?关于如何获取返回的数据的任何想法,而不仅仅是状态码?
public void requestWithSomeHttpHeaders() {
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://......";
JSONObject jsonBody = new JSONObject();
jsonBody.put("username", "yourusername");
jsonBody.put("password", "yourpassword");
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "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
System.out.println(responseString);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
优选地,定义一种方法。
private void doLogin() {
// TODO: startActivity?
}
然后打电话给
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
doLogin();
}
如果要从服务器获取数据,那String response
就是。检查您的Logcat。
正如在评论中提到的,使用StringRequest
不执行getBody
,parseNetworkResponse
以及getBodyContentType
可以更好地工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句