- How to Set Custom User Agent in Android WebView
- Set Custom User Agent Android WebView
- Create a new string
- Meet Advanced Plus
- User-Agent Strings
- # Chrome for Android
- # Chrome for iOS
- # WebView on Android
- Android studio user agent
- About
- How to Correctly Form User-Agents for Mobile Apps
- The User-Agent
- How to form a meaningful User-Agents for mobile apps
- Native Android App
- Native iOS App
- Objective-C
- Swift
- Windows Phone
- Final Thoughts
- Android Generic User Agent (UA)
- 5 ответов
How to Set Custom User Agent in Android WebView
Set Custom User Agent Android WebView
Updated on: June 29, 2021
In webview of Android, if you want to set custom user agent,this tutorial is for you.
Custom user agent can be helpful if some options of a website is only available in the desktop version of the site – not on mobile version, or you just want your app to have the option to change user agent, etc
To set a custom user agent, we need define the user agent in a string, then pass the string to setUserAgentString(your string name here).
Create a new string
In the activity of the webview, create a new string,
So we created a string for user agent, the user agent defined in the string is of a desktop browser user agent, with this user agent set – your Android browser will load desktop version of websites. You can change this user agent to other user agents you like.
So we set the string, now let’s call it
Here we called the string that we have set, it is ready now.
This code can be inside the oncreate method of the web activity.
Meet Advanced Plus
I highly recommend you use the new and advanced Android Webview Advanced Plus Source Code we developed to easily convert any website to android app. No coding required, just set your website link, app color, icon etc and the app will be ready!, and it supports upload, download, loading progress bars, notification, night mode etc. To learn more about the Android Advanced Webview Source Code and to download it, head over to this page Download Android Webview Source Code
Источник
User-Agent Strings
Published on Friday, February 28, 2014 • Updated on Tuesday, November 9, 2021
With Privacy Sandbox, an origin trial is in progress for reduced User-Agent strings, designed to remove sensitive information which may be used for fingerprinting.
A browser’s User-Agent string (UA) helps identify which browser is being used, what version, and on which operating system. When feature detection APIs are not available, use the UA to customize behavior or content to specific browser versions.
Like all other browsers, Chrome for Android sends this information in the User-Agent HTTP header every time it makes a request to any site. It’s also available in the client through JavaScript using the navigator.userAgent call.
# Chrome for Android
Chrome for Android reports its UA in the following formats, depending on whether the device is a phone or a tablet.
Phone UA:
Tablet UA:
Here’s an example of the Chrome user agent string on a Galaxy Nexus:
If you are parsing user agent strings using regular expressions, the following can be used to check against Chrome on Android phones and tablets:
- Phone pattern: ‘Android’ + ‘Chrome/[.0-9]* Mobile’
- Tablet pattern: ‘Android’ + ‘Chrome/[.0-9]* (?!Mobile)’
# Chrome for iOS
The UA in Chrome for iOS is the same as the Mobile Safari user agent, with CriOS/ instead of Version/ .
Here’s an example of the Chrome UA on iPhone:
For comparison, the Mobile Safari UA:
Up to Chrome 84, when the Request Desktop Site feature is enabled, the Desktop Safari UA is sent:
Starting from Chrome 85, when the Request Desktop Site feature is enabled, the UA is the same as the Desktop Safari UA with CriOS/ being added:
# WebView on Android
The Android 4.4 (KitKat) Chromium-based WebView adds Chrome/_version_ to the user agent string.
WebView UA in KitKat to Lollipop
If you’re attempting to differentiate between the WebView and Chrome for Android, you should look for the presence of the Version/_X.X_ string in the WebView user-agent string. Don’t rely on the specific Chrome version number (for example, 30.0.0.0) as the version numbers changes with each release.
WebView UA in Lollipop and Above
In the newer versions of WebView, you can differentiate the WebView by looking for the wv field as highlighted below.
With Privacy Sandbox, an origin trial is in progress for reduced User-Agent strings, designed to remove sensitive information which may be used for fingerprinting.
Last updated: Tuesday, November 9, 2021 Improve article
Источник
Android studio user agent
Android User Agent Android Library
Library that generates User-Agent string for http requests.
Purpose of this library
In Ackee, we need more info in User-Agent header than standard System.getProperty(«http.agent») provides and purpose of this library is to provide better one. The format of our User-Agent is
so example of one of our application
Usage is very simple, basically this whole library is just one singleton class. Because of abstraction from http library you use there is need for passing user agent string of this library. We are practically everywhere using OkHttp but who knows.
Example in OkHttp interceptor
Version.userAgent() is getter for OkHttp string like okhttp/3.2.0
Copyright 2021 Ackee, s.r.o.
Licensed under the Apache License, Version 2.0 (the «License»); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
About
Library that generates User-Agent string for http requests
Источник
How to Correctly Form User-Agents for Mobile Apps
Nov 15th, 2017
Native apps, Mobile apps, or just apps. We call them different things and we use them all the time. From a business perspective, apps complement mobile and desktop sites. They are natural extension of an online strategy. Because of this, it’s important to take the necessary steps to make sure the native apps, and their versions, are identifiable. This is critical both from an analytics perspective as well as from a devops or support perspective. Native apps have much in common with the web. Apps often use the same online resources as the web site like RESTful APIs, images or videos. Because these resources are shared, it is very important to correctly form User-Agents for mobile apps to identify who is using the resources. Is the user on the Android app or iOS app? Which version of the app? Which OS version? And so on.
There are two kinds of mobile apps: 1) fully native apps, and 2) webview-based hybrid apps. In this post, we will focus on fully native apps where HTTP requests are sent by the native code.
If you are interested in webview-based hybrid apps where a browser window is wrapped in a native shell, then check out this other post on User-Agent strings for hybrid webview apps.
The User-Agent
There is already an industry standard for device identification that apps can also use. It’s the User-Agent string. The User-Agent string is a field in the HTTP header that can identify the app that is making the request. In a web browsing experience, the User-Agent is set by the browser (which is also an app). Now, instead of a browser, our native app will be making the HTTP request. When we’re developing a native app for a mobile phone, we need to take steps to ensure our User-Agent includes information that is meaningful. Otherwise the app will get the default values, which is not very helpful in any context.
How to form a meaningful User-Agents for mobile apps
The “User-Agent” header field contains information about the user agent originating the request, which is often used by servers to help identify the scope of reported interoperability problems, to work around or tailor responses to avoid particular user agent limitations, and for analytics regarding browser or operating system use.
The specification goes in more detail and concludes that User-Agents should consist of one or more product identifiers and optional versions. By convention, the product identifiers are listed in decreasing order of their significance for identifying the User-Agent software.
Let’s dive right in and see how to compose meaningful User-Agent strings for native apps in the different platforms:
Native Android App
Based on the specification above, the template we want for the User-Agent of our app is:
The significant part here is “Myapp/1” which identifies the native app and the version of the app. This is the most significant. The rest of the string identifies the underlying software. In Android, it is relatively easy to compose a custom User-Agent string. Here is some sample code:
If you’re using the popular Picasso library, then the composition is similar. However, the actual request is made in a slightly different way. Have a look a this example app built with Picasso on Github.
Native iOS App
User-Agents for iOS are slightly more complex due to the fact that we have to account for both Objective-C and Swift. A default User-Agent in iOS may look something like this:
In iOS a component called “CFNetwork” handles the network communications. Also involved is the UNIX version iOS is built on: “Darwin”. Both of these are mentioned in the default User-Agent. In addition there may be a custom app identifier added. So not very meaningful.
In order to construct a more meaningful User-Agent we need more information added to it, like so:
The main challenge in constructing the User-Agent in iOS is to collect all the parameters needed. For example, it is not obvious how to find the CFNetwork- and Darwin values. We’ve wrote an example app in Objective-C and Swift with the functionality needed to gather all bits that go into the User-Agent string. Feel free to use it. Once the bits are collected, just call the function to compose the User-Agent before you make a request:
Objective-C
For full code of the getUAString() function, see Github.
Swift
For full code of the getUAString() function, see Github.
Windows Phone
Even if not as popular as Android and iOS, Windows Phone is also worth mentioning. The semantic of the User-Agent is similar:
You can get the device brand name and model name from the EasClientDeviceInformation class with the SystemManufacturer and SystemProductName properties. The OS version can be extracted from DeviceFamilyVersion property in the AnalyticsVersionInfo class.
Final Thoughts
Even if your favorite library or framework is not covered in this post, these examples should be generic enough to be transferred to any framework. It’s worth spending the additional few minutes of development to make sure the User-Agent of your app is meaningful and conforms to specification. Your analytics, devops, and debugging will all benefit. And likewise, you can leverage this device detection to target specific devices, apps, or app versions on specific platforms with messages, ads or content.
This article covered User-Agents in fully native apps. If your app is a webview based app (or hybrid app), then read “Correctly Form User-Agents for Webview Apps”
Источник
Android Generic User Agent (UA)
Я создаю приложение для Android для отображения контента с сервера. Сервер представляет собой мобильный веб-сайт (например,http://m.google.com) который отслеживает трафик от различных мобильных клиентов. Чтобы дифференцировать клиент Android, как предоставить общую строку для моего приложения?
вот почему я прошу:
некоторые Android устройств у меня есть УА строк типа:
Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; ADR6400L 4G Build/FRG83D) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
Mozilla / 5.0 (Linux; U; Android 2.1; ru-us; Eclair_spr Build / 30201) AppleWebKit / 520.17 (KHTML, like Gecko) версия / 4.0 мобильное сафари/520.17
мне нужно добавить строку в строку UserAgent для идентификации моего приложения. Например:
мне нужно сделать что-то подобное: Mozilla/5.0 (Linux; U; Android 2.1; en-us; Eclair_SPR Build/30201) AppleWebKit/520.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/520.17 Android_MyFirstApp .
это правильный способ сделать это?
5 ответов
чтобы изменить пользовательский агент, вам нужно отправить пользовательский заголовок User-Agent: с вашим HTTP-запросом. Предполагая, что вы используете Android org.апаш.http.клиент.Класс HttpClient, у вас есть два варианта:
- установите заголовок агента пользователя для каждого запроса. Вы делаете это, вызывая setHeader () на объекте HttpRequest (HttpPost, HttpGet, whatever) после его создания:
- измените параметр агента пользователя по умолчанию, который повлияет на все будущее экземпляры этого класса HttpClient. Вы делаете это, читая коллекцию HttpParams из своего клиента с помощью getParams (), а затем обновляя агент пользователя с помощью setParameter ():
Если вы хотите добавить вместо замены агента пользователя, вы можете сначала прочитать существующий, изменить его и установить его обратно с помощью любого из вышеуказанных методов.
поскольку вы сказали, что используете представление WebView, вам нужно будет использовать настройку WebSettings момент не существует. Это один и тот же процесс. Перед вызовом метода load () (loadUrl, loadData и т. д.) Вы устанавливаете агент пользователя. Измененный пользовательский агент будет сохраняться до тех пор, пока этот экземпляр WebView находится рядом, поэтому вы сделаете это в onCreate() вашей активности:
опять же, если вы хотите добавить вместо замены, используйте getUserAgentString (), чтобы прочитать его, затем обновите его и снова установите.
поскольку вы управляете своим клиентом Android, почему бы вам не создать общую строку заголовка и не установить ее в заголовке каждый раз, когда ваше приложение делает вызов сервера? Таким образом, вы можете убедиться, что строка уникальна, а также добавить любую другую полезную информацию для отправки на сервер. Вы должны иметь возможность использовать webView.loadUrl() для установки дополнительных заголовков.
вы можете полностью сделать это и на developer.android.com предложите это также, когда они говорят о WebView, особенно если вы хотите создать веб-приложение для своего веб-представления. Ссылка здесь: http://developer.android.com/guide/webapps/webview.html
Id предлагает не только сохранить ссылку на приложение в вашем агенте пользователя, но и отслеживать версию.
в любом случае, я хотел бы изменить свой UA тоже и обсуждения здесь и поощрял меня делать то же самое.
вот моя реализация:
на вашем Android приложение:
если вы хотите автоматически увеличить номер сборки aka. versionCode вы можете взглянуть на этот другой Переполнение Стека сообщение, а также решение C#.
после этого вы просто измените пользовательский агент.
в вашем веб-приложении: в PHP
Или В В JavaScript
или вы можете сразу обнаружить его от .реврайт:
Это зависит от того, какие рамки вы используете, чтобы сделать ваши запросы. Если вы используете org.apache классы, вы можете позвонить setHeader(‘User-Agent’, «Generic user agent here») на HttpMessage вы используете для выполнения вашего запроса.
когда вы используете веб-представление для доступа к User-agent, убедитесь, что вы запустили
в потоке пользовательского интерфейса.
Если вы хотите получить доступ к агенту пользователя в фоновом потоке. использовать
Источник