mattak's blog

気の向くままに書く

volley でuseragentを設定

よくわかんにゃかったので、よんだ。

    30  public class Volley {
    ....
    35      /**
    36       * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
    37       *
    38       * @param context A {@link Context} to use for creating the cache dir.
    39       * @param stack An {@link HttpStack} to use for the network, or null for default.
    40       * @return A started {@link RequestQueue} instance.
    41       */
    42      public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    43          File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
    44  
    45          String userAgent = "volley/0";
    46          try {
    47              String packageName = context.getPackageName();
    48              PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
    49              userAgent = packageName + "/" + info.versionCode;
    50          } catch (NameNotFoundException e) {
    51          }
    52  
    53          if (stack == null) {
    54              if (Build.VERSION.SDK_INT >= 9) {
    55                  stack = new HurlStack();
    56              } else {
    57                  // Prior to Gingerbread, HttpUrlConnection was unreliable.
    58                  // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
    59                  stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
    60              }
    61          }
    62  
    63          Network network = new BasicNetwork(stack);
    64  
    65          RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    66          queue.start();
    67  
    68          return queue;
    69      }

HttpStackがnullのとき、 volleyではapi level 9以上は HttpURLConnection, それ以外は Apache HttpClientを利用している。 api level 8でuser agentを利用するには自分でHttpStackを定義する必要がある。

HurlStackを読んでみる

    46  /**
    47   * An {@link HttpStack} based on {@link HttpURLConnection}.
    48   */
    49  public class HurlStack implements HttpStack {
    ...
    87      @Override
    88      public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
    89              throws IOException, AuthFailureError {
    90          String url = request.getUrl();
    91          HashMap<String, String> map = new HashMap<String, String>();
    92          map.putAll(request.getHeaders());
    93          map.putAll(additionalHeaders);
    ...
   102          HttpURLConnection connection = openConnection(parsedUrl, request);
   103          for (String headerName : map.keySet()) {
   104              connection.addRequestProperty(headerName, map.get(headerName));
   105          }
    ...
   125          return response;
   126      }

user agentを設定しているのは以下の部分.

   104              connection.addRequestProperty(headerName, map.get(headerName));

わたってきたヘッダの値を設定しているだけなので、Requestを以下のように利用する

    Request request = new StringRequest(
            Request.Method.GET,
            "http://www.google.com",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    // handle response
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    // handle error response
                }
            }) {
        public Map<String, String> getHeaders() {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.0.4; ja-jp; SC-06D Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
            return headers;
        }
    };