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 17 package com.android.volley.toolbox; 18 19 import com.android.volley.NetworkResponse; 20 import com.android.volley.Request; 21 import com.android.volley.Response; 22 import com.android.volley.Response.ErrorListener; 23 import com.android.volley.Response.Listener; 24 25 import java.io.UnsupportedEncodingException; 26 27 /** 28 * A canned request for retrieving the response body at a given URL as a String. 29 */ 30 public class StringRequest extends Request<String> { 31 private final Listener<String> mListener; 32 33 /** 34 * Creates a new request. 35 * @param url URL to fetch the string at 36 * @param listener Listener to receive the String response 37 * @param errorListener Error listener, or null to ignore errors 38 */ StringRequest(String url, Listener<String> listener, ErrorListener errorListener)39 public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) { 40 super(url, errorListener); 41 mListener = listener; 42 } 43 44 @Override deliverResponse(String response)45 protected void deliverResponse(String response) { 46 mListener.onResponse(response); 47 } 48 49 @Override parseNetworkResponse(NetworkResponse response)50 protected Response<String> parseNetworkResponse(NetworkResponse response) { 51 String parsed; 52 try { 53 parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); 54 } catch (UnsupportedEncodingException e) { 55 parsed = new String(response.data); 56 } 57 return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); 58 } 59 } 60