來自伺服器的布林變數響應,帶有 json 請求
你可以在一個以下定製類
private final String PROTOCOL_CONTENT_TYPE = String.format("application/json; charset=%s", PROTOCOL_CHARSET);
public BooleanRequest(int method, String url, String requestBody, Response.Listener<Boolean> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
this.mRequestBody = requestBody;
}
@Override
protected Response<Boolean> parseNetworkResponse(NetworkResponse response) {
Boolean parsed;
try {
parsed = Boolean.valueOf(new String(response.data, HttpHeaderParser.parseCharset(response.headers)));
} catch (UnsupportedEncodingException e) {
parsed = Boolean.valueOf(new String(response.data));
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return super.parseNetworkError(volleyError);
}
@Override
protected void deliverResponse(Boolean response) {
mListener.onResponse(response);
}
@Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
@Override
public String getBodyContentType() {
return PROTOCOL_CONTENT_TYPE;
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
mRequestBody, PROTOCOL_CHARSET);
return null;
}
}
}
將此用於你的活動
try {
JSONObject jsonBody;
jsonBody = new JSONObject();
jsonBody.put("Title", "Android Demo");
jsonBody.put("Author", "BNK");
jsonBody.put("Date", "2015/08/28");
String requestBody = jsonBody.toString();
BooleanRequest booleanRequest = new BooleanRequest(0, url, requestBody, new Response.Listener<Boolean>() {
@Override
public void onResponse(Boolean response) {
Toast.makeText(mContext, String.valueOf(response), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext, error.toString(), Toast.LENGTH_SHORT).show();
}
});
// Add the request to the RequestQueue.
queue.add(booleanRequest);
} catch (JSONException e) {
e.printStackTrace();
}