Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection in android doesn't send correct User-Agent header [closed]

I have found an issue. I have a server that uses User Agent header to identify the device that is connecting to it. But when i connect to the server using HttpURLConnection i get no User Agent header, but when i connect with the browser it sends the correct User Agent.

For testing i am using an echo server that replies with the headers it found on the request.

When i connect with browser i get: eg: User-Agent: Mozilla/5.0 (Linux; U; Android 1.5; en-fr; HTC Hero Build/CUPCAKE) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1 Up.Link/6.3.1.20.06.3.1.20.0.

But when i connect by code with UrlConnection i get:

User-Agent: UNAVAILABLE.

Does anyone know we i get different behaviors? How i can i connect in the same way the browser does?

EDIT:

What i really need is not only the User-Agent header, i also need some special headers (x-up-subno actually). This header is added by the APN of the operator, but for some reason when i connect by code that headers are not added to the request.

From browser: browser

From code: code

Thanks,

like image 842
Lucas S. Avatar asked Sep 15 '09 22:09

Lucas S.


People also ask

What is HTTP URL connection in Android?

HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called. Other HTTP methods ( OPTIONS , HEAD , PUT , DELETE and TRACE ) can be used with setRequestMethod(String) .

Is User Agent a header?

The user agent is an HTTP header that web browsers and other web applications use to identify themselves and their capabilities.

What does the very User Agent HTTP header do?

The User-Agent request header is a characteristic string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting user agent.


1 Answers

The HTTP specification states that all clients are supposed to sent User-Agent headers. It however, does not state that they should identify the client in the manner a server wishes to. Android therefore complies with the specification, and there is not a lot you can do about it.

The best you could do is to use the setRequestProperty() method to attempt to get a preferable user-agent value in the request. There are no guarantees that it would work, but it is likely. The method needs to be called in the following manner:

connection.setRequestProperty("User-Agent","MyAppName/1.0");

The stock Android browser uses WebKit. If you want to set WebKit's user-agent string, you'll either have to use a static value, or read the user-agent string from WebKit. I haven't attempted this, but the WebKit user-agent string is available in Android via the getUserAgentString() method of the WebSettings class.

like image 152
Vineet Reynolds Avatar answered Oct 06 '22 08:10

Vineet Reynolds