- HttpURLConnection: Android Tutorial
- Integrating HttpURLConnection
- Full project code and final thoughts
- HttpURLConnection: Подключаемся к URL
- Знакомство с классом HttpURLConnection
- Android HttpURLConnection Example
- 1. HttpURLConnection use steps.
- 2. HttpURLConnection Examples.
- 2.1 Main Activity.
- 2.2 Main Layout Xml File.
- 2.3 Android Manifest Xml File.
- HttpURLConnection
- Class Overview
- Secure Communication with HTTPS
- Response Handling
- Posting Content
- Performance
- Handling Network Sign-On
- HTTP Authentication
- Sessions with Cookies
- HTTP Methods
- Proxies
- IPv6 Support
- Response Caching
- Avoiding Bugs In Earlier Releases
- Summary
- Constants
- public static final int HTTP_ACCEPTED
- public static final int HTTP_BAD_GATEWAY
- public static final int HTTP_BAD_METHOD
- public static final int HTTP_BAD_REQUEST
- public static final int HTTP_CLIENT_TIMEOUT
- public static final int HTTP_CONFLICT
- public static final int HTTP_CREATED
- public static final int HTTP_ENTITY_TOO_LARGE
- public static final int HTTP_FORBIDDEN
- public static final int HTTP_GATEWAY_TIMEOUT
- public static final int HTTP_GONE
- public static final int HTTP_INTERNAL_ERROR
- public static final int HTTP_LENGTH_REQUIRED
- public static final int HTTP_MOVED_PERM
- public static final int HTTP_MOVED_TEMP
- public static final int HTTP_MULT_CHOICE
- public static final int HTTP_NOT_ACCEPTABLE
- public static final int HTTP_NOT_AUTHORITATIVE
- public static final int HTTP_NOT_FOUND
- public static final int HTTP_NOT_IMPLEMENTED
- public static final int HTTP_NOT_MODIFIED
- public static final int HTTP_NO_CONTENT
- public static final int HTTP_OK
- public static final int HTTP_PARTIAL
- public static final int HTTP_PAYMENT_REQUIRED
- public static final int HTTP_PRECON_FAILED
- public static final int HTTP_PROXY_AUTH
- public static final int HTTP_REQ_TOO_LONG
- public static final int HTTP_RESET
- public static final int HTTP_SEE_OTHER
- public static final int HTTP_SERVER_ERROR
- public static final int HTTP_UNAUTHORIZED
- public static final int HTTP_UNAVAILABLE
- public static final int HTTP_UNSUPPORTED_TYPE
- public static final int HTTP_USE_PROXY
- public static final int HTTP_VERSION
HttpURLConnection: Android Tutorial
Most of internet content distribution it is still done through HTTP, which means that anyone building a mobile app will be obviously dealing with HTTP Libs. Since we are working to improve the performance of content distribution on mobile apps (find more about it here), there was no doubt that our Bolina SDK would have to be seamlessly integrated with, at least, the most popular HTTP Libs out there. That was how I decided to start exploring the HTTP Libs landscape (all tutorials and performance-related articles, here).
HttpURLConnection was one of the first libs I’ve decided to integrate, and it is easy to know why: ever since Android API 9, HttpURLConnection has become the recommended HTTP library for Android applications. Here’s what I’ve learned, how to integrate it and some caveats that every developer should take into consideration.
I am integrating it into a clean, straight out of the Android Studio new project wizard. This tutorial will create 2 HTTP calls, a GET and a POST to a publicly available RESTful API, hosted by reqres.in, a service “that allows us to test our front-end against a real API”.
Integrating HttpURLConnection
Starting integrating HttpURLConnection is simple, given that the HTTP library is included in the Android API since API 1. However, we must take into consideration the fact that the library is not prepared for native asynchronous calls, requiring us to make use of workers, such as AsyncTasks, to perform HTTP network calls outside the main UI thread.
First, add the permission to the application’s manifest to allow the application to access the Internet:
Now let’s create an AsyncTask to perform an HTTP GET call:
If you are familiar with Android development, this class is pretty straightforward. The main logic of the worker is located inside the doInBackground method. First, I set the desired URL, followed by establishing an HTTP connection, via the openConnection method. After checking if the connection was successful, I read the connection’s data from a BufferedReader, in this case, reading it, line by line. And that’s it!
To call this HTTP GET worker, just start the AsyncTask, for instance on the onCreate method of the main activity:
To perform a POST call, just create the following AsyncTask:
The first thing I do is create JSON data to post to the service. To create JSON data, we need to include the gradle dependency:
Then create the URL of the post to be performed, followed by establishing the HTTP connection. Next, I set the HttpURLConnection options to perform the POST and write the JSON data into the connection. Finally, I just check if the post was successfully received by the server and check the server’s reply. Again, simple!
As previously, to run this worker, just call it from anywhere in your project, via:
Full project code and final thoughts
The full code used is available at Github. Feel free to adapt the code according to your specific needs. I hope this helped you integrating HttpURLConnection into an Android project, performing GET and POST calls, and understanding how to properly used it outside the main UI thread, via an AsyncTask.
In the end, HttpURLConnection is a mature HTTP library that can be integrated with relative ease, even though I have to admit that I prefer approaches like the more modern OkHttp library (Integration Tutorial). Since it provides native asynchronous methods, it significantly simple to integrate it on a project. However, I can’t deny that performance is my main concern (and interest), so I had to find out which one was faster. Would you bet on HttpURLConnection or OkHttp? Check my results here and find out!
Источник
HttpURLConnection: Подключаемся к URL
4-й курс/закрытая зона
Знакомство с классом HttpURLConnection
Для соединения с веб-серверами Android предлагает несколько способов взаимодействия. В новых проектах для современных устройств рекомендуется использовать класс HttpURLConnection, который мы с вами рассмотрим на примерах.
Класс java.net.HttpURLConnection является подклассом java.net.URLConnection и позволяет реализовать работу по отправке и получении данных из сети по протоколу HTTP. Данные могут быть любого типа и длины. Данный класс следует использовать для отправки и получения потоковых данных, размеры которых нельзя заранее определить. Используя данный класс, вам не нужно думать о сокетах и реализовывать собственные способы общения между клиентом и сервером.
Алгоритм использования следующий:
- Получить объект HttpURLConnection через вызов URL.openConnection() и привести результат к HttpURLConnection
- Подготовить необходимый запрос. Основное в запросе — сам сетевой адрес. Также в запросе можно указать различные метаданные: учётные данные, тип контента, куки сессии и т.п.
- Опционально загрузить тело запроса. В этом случае используется метод setDoOutput(true). Передача данных, записанных в поток, возвращается через метод getOutputStream()
- Прочитать ответ. Заголовок ответа обычно включает метаданные, такие как тип и длина контента, даты изменения, куки сессии. Прочитать данные из потока можно через метод getInputStream(). Если у ответа нет тела, то метод возвращает пустой поток.
- Разорвать соединение. После прочтения ответа от сервера HttpURLConnection следует закрыть через вызов метода disconnect(). Тем самым вы освобождаете ресурсы, занимаемые соединением.
Например, для получения страницы по адресу http://developer.alexanderklimov.ru/android/ можно использовать такой код:
По умолчанию HttpURLConnection использует метод GET. Для использования POST вызывайте setDoOutput(true) и посылайте данные через openOutputStream(). Другие HTTP-методы (OPTIONS, HEAD, PUT, DELETE and TRACE) настраиваются через метод setRequestMethod(String).
Для работы через прокси-сервер используйте URL.openConnection(Proxy) при создании соединения.
Каждый экземпляр HttpURLConnection может использоваться только для одной пары запроса/ответа. Операции с соединениями следует проводить в отдельном потоке.
Вы вошли на сайт, как гость.
Необходимо зарегистрироваться, чтобы прочитать статью
Источник
Android HttpURLConnection Example
This article will tell you how to use java.net.HttpURLConnection class to send http request and get http server response in android application.
1. HttpURLConnection use steps.
- Create a URL instance.
- Open url connection and cast it to HttpURLConnection.
- Set request method. The request method can be GET, POST, DELETE etc. Request method must be uppercase, otherwise below exception will be thrown. java.net.ProtocolException: Expected one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH] but was get
- If request method is GET, then use below code to open input stream and read server response data.
- For POST request method, use below code to open output stream to the server url and write post data to it. After post, open the input stream again to get server response.
- After use HttpURLConnection, do not forget close related reader or writer and call HttpURLConnection’s disconnect() method to close the connection to release network resources.
2. HttpURLConnection Examples.
If you can not watch the above video, you can see it on the youtube URL https://youtu.be/cCvEVf-OUU4
In this example, read server response process is occurred in a child thread. The child thread send a message to activity main thread’s Handler object to update the response data in TextView.
This is because child thread can not update UI controls in activity directly, otherwise an error will happen.
2.1 Main Activity.
2.2 Main Layout Xml File.
2.3 Android Manifest Xml File.
Because this example will connect network resources, so you need to declare below permission in android manifest xml file.
Источник
HttpURLConnection
java.lang.Object | ||
↳ | java.net.URLConnection | |
↳ | java.net.HttpURLConnection |
Class OverviewAn URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance. Uses of this class follow a pattern:
For example, to retrieve the webpage at http://www.android.com/ : Secure Communication with HTTPSResponse HandlingIf the HTTP response indicates that an error occurred, getInputStream() will throw an IOException . Use getErrorStream() to read the error response. The headers can be read in the normal way using getHeaderFields() , Posting ContentFor best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance, or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly exhausting) heap and increasing latency. For example, to perform an upload: PerformanceWhen transferring large amounts of data to or from a server, use streams to limit how much data is in memory at once. Unless you need the entire body to be in memory at once, process it as a stream (rather than storing the complete body as a single byte array or string). To reduce latency, this class may reuse the same underlying Socket for multiple request/response pairs. As a result, HTTP connections may be held open longer than necessary. Calls to disconnect() may return the socket to a pool of connected sockets. This behavior can be disabled by setting the http.keepAlive system property to false before issuing any HTTP requests. The http.maxConnections property may be used to control how many idle connections to each server will be held. By default, this implementation of HttpURLConnection requests that servers use gzip compression and it automatically decompresses the data for callers of getInputStream() . The Content-Encoding and Content-Length response headers are cleared in this case. Gzip compression can be disabled by setting the acceptable encodings in the request header: Setting the Accept-Encoding request header explicitly disables automatic decompression and leaves the response headers intact; callers must handle decompression as needed, according to the Content-Encoding header of the response. getContentLength() returns the number of bytes transmitted and cannot be used to predict how many bytes can be read from getInputStream() for compressed streams. Instead, read that stream until it is exhausted, i.e. when read() returns -1. Handling Network Sign-OnHTTP AuthenticationSessions with CookiesThe default CookieManager keeps all accepted cookies in memory. It will forget these cookies when the VM exits. Implement CookieStore to define a custom cookie store. In addition to the cookies set by HTTP responses, you may set cookies programmatically. To be included in HTTP request headers, cookies must have the domain and path properties set. By default, new instances of HttpCookie work only with servers that support RFC 2965 cookies. Many web servers support only the older specification, RFC 2109. For compatibility with the most web servers, set the cookie version to 0. For example, to receive www.twitter.com in French: HTTP MethodsHttpURLConnection 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) . ProxiesIPv6 SupportThis class includes transparent support for IPv6. For hosts with both IPv4 and IPv6 addresses, it will attempt to connect to each of a host’s addresses until a connection is established. Response CachingAvoiding Bugs In Earlier ReleasesEach instance of HttpURLConnection may be used for one request/response pair. Instances of this class are not thread safe. Summary
|