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 with the given method.
35     *
36     * @param method the request {@link Method} to use
37     * @param url URL to fetch the string at
38     * @param listener Listener to receive the String response
39     * @param errorListener Error listener, or null to ignore errors
40     */
41    public StringRequest(int method, String url, Listener<String> listener,
42            ErrorListener errorListener) {
43        super(method, url, errorListener);
44        mListener = listener;
45    }
46
47    /**
48     * Creates a new GET request.
49     *
50     * @param url URL to fetch the string at
51     * @param listener Listener to receive the String response
52     * @param errorListener Error listener, or null to ignore errors
53     */
54    public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) {
55        this(Method.GET, url, listener, errorListener);
56    }
57
58    @Override
59    protected void deliverResponse(String response) {
60        mListener.onResponse(response);
61    }
62
63    @Override
64    protected Response<String> parseNetworkResponse(NetworkResponse response) {
65        String parsed;
66        try {
67            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
68        } catch (UnsupportedEncodingException e) {
69            parsed = new String(response.data);
70        }
71        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
72    }
73}
74