Replace appname in user-agent with volleyball

How can I change the User-Agent in the request header with the application name in the first user-agent section as follows: Myappname (Linux; U; Android 4.3; Galaxy Nexus Build/JWR66Y)

Please note that I do not want to change other parameters in the user-agnet line

I used a volley for requests.

Any suggestion to do this dynamically?

+4
source share
2 answers

I wanted to do EXACTLY the same in my Android app. Namely, change the User-Agent header, but just add / add something and leave the "original" content (or most of it).

@athor , , userAgent, HttpClientStack, , API Android 8, ( , ). API 9 HurlStack, , , newRequestQueue, , , HurlStack, OkHttpStack. userAgent, , , , .

, , Volley Request<T>, getHeaders User-Agent. , User-Agent.

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = super.getHeaders();
    if (headers == null || headers.equals(Collections.emptyMap())) {
        headers = new HashMap<String, String>();
    }
    if (context != null) {
        StringBuilder label = new StringBuilder();
        label.append(context.getApplicationInfo().loadLabel(context.getPackageManager()));
        label.append("/");
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            label.append(pInfo.versionName);
        } catch (NameNotFoundException e) {
        }
        label.append(" ");
        label.append(System.getProperty("http.agent"));
        headers.put("User-Agent", label.toString());
    }
    return headers;
}

, System.getProperty("http.agent") "" User-Agent, . , , Dalvik/1.6.0, , 100% . , Android Context .

, !

+4

Volley newRequestQueue.

 public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new ManualProxyNetwork(new BasicNetwork(stack));

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}

- , . 1 . newRequestQueue .

+1

Source: https://habr.com/ru/post/1532040/


All Articles