1/* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.volley.toolbox; 18 19import com.android.volley.NetworkResponse; 20import com.android.volley.ParseError; 21import com.android.volley.Response; 22import com.android.volley.Response.ErrorListener; 23import com.android.volley.Response.Listener; 24 25import org.json.JSONException; 26import org.json.JSONObject; 27 28import java.io.UnsupportedEncodingException; 29 30/** 31 * A request for retrieving a {@link JSONObject} response body at a given URL, allowing for an 32 * optional {@link JSONObject} to be passed in as part of the request body. 33 */ 34public class JsonObjectRequest extends JsonRequest<JSONObject> { 35 36 /** 37 * Creates a new request. 38 * @param url URL to fetch the JSON from 39 * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and 40 * indicates no parameters will be posted along with request. 41 * @param listener Listener to receive the JSON response 42 * @param errorListener Error listener, or null to ignore errors. 43 */ 44 public JsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener, 45 ErrorListener errorListener) { 46 super(url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener); 47 } 48 49 @Override 50 protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { 51 try { 52 String jsonString = 53 new String(response.data, HttpHeaderParser.parseCharset(response.headers)); 54 return Response.success(new JSONObject(jsonString), 55 HttpHeaderParser.parseCacheHeaders(response)); 56 } catch (UnsupportedEncodingException e) { 57 return Response.error(new ParseError(e)); 58 } catch (JSONException je) { 59 return Response.error(new ParseError(je)); 60 } 61 } 62} 63