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.Request;
21import com.android.volley.Response;
22import com.android.volley.Response.ErrorListener;
23import com.android.volley.Response.Listener;
24
25import java.io.UnsupportedEncodingException;
26
27/**
28 * A canned request for retrieving the response body at a given URL as a String.
29 */
30public 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     */
39    public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) {
40        super(url, errorListener);
41        mListener = listener;
42    }
43
44    @Override
45    protected void deliverResponse(String response) {
46        mListener.onResponse(response);
47    }
48
49    @Override
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