我正在尝试在我的应用程序中获取一些数据并通过使用与Volley的HTTP POST请求向用户显示。 我的问题是我不知道如何获得服务器Body对请求的响应。在下面的代码中,响应总是" 200"它变为HTTP状态代码。
如何提取身体反应并以字符串形式管理?
RequestQueue requestQueue = Volley.newRequestQueue(this);
final String requestBody = Utility.toCorrectCase(req);
//Decommentare solo per il debug
//Toast.makeText(getBaseContext(),requestBody, Toast.LENGTH_SHORT).show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
Bitmap myBitmap = QRCode.from(response).bitmap();
qrcode.setImageBitmap(myBitmap);
ViewGroup.LayoutParams params = qrcode.getLayoutParams();
params.width = qrDisplayedSize;
params.height = qrDisplayedSize;
qrcode.setLayoutParams(params);
loadingText.setText(getString(R.string.prod_id_desc).concat(response));
qrcode.setVisibility(View.VISIBLE);
backButton.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.INVISIBLE);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("VOLLEY", error.toString());
new SweetAlertDialog(getApplicationContext(), SweetAlertDialog.ERROR_TYPE)
.setTitleText("Errore comunicazione server")
.setContentText("Qualcosa non ha funzionato!\nDescrizione errore:".concat(error.toString()))
.show();
finish();
}
}) {
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=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;
responseString = String.valueOf(response.statusCode);
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
答案 0 :(得分:2)
经过几天的搜索,我发现我没有正确覆盖networkResponse。因此,对于遇到同样问题的每个人,我的问题的答案是:必须重写parseNetworkResponse才能以最简单的方式获取响应主体。
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
if(response.statusCode==400){
new SweetAlertDialog(getApplicationContext(), SweetAlertDialog.ERROR_TYPE)
.setTitleText("Errore comunicazione server")
.setContentText("Qualcosa non ha funzionato!\nCodice errore:"+response.statusCode)
.show();
finish();
}
return super.parseNetworkResponse(response);
}
答案 1 :(得分:1)
改变它对我有用
@Override
protected Response < String > parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}