Urlconnection in android studio

Содержание
  1. HttpURLConnection: Android Tutorial
  2. Integrating HttpURLConnection
  3. Full project code and final thoughts
  4. HttpURLConnection: Подключаемся к URL
  5. Знакомство с классом HttpURLConnection
  6. Android HttpURLConnection Example
  7. 1. HttpURLConnection use steps.
  8. 2. HttpURLConnection Examples.
  9. 2.1 Main Activity.
  10. 2.2 Main Layout Xml File.
  11. 2.3 Android Manifest Xml File.
  12. HttpURLConnection
  13. Class Overview
  14. Secure Communication with HTTPS
  15. Response Handling
  16. Posting Content
  17. Performance
  18. Handling Network Sign-On
  19. HTTP Authentication
  20. Sessions with Cookies
  21. HTTP Methods
  22. Proxies
  23. IPv6 Support
  24. Response Caching
  25. Avoiding Bugs In Earlier Releases
  26. Summary
  27. Constants
  28. public static final int HTTP_ACCEPTED
  29. public static final int HTTP_BAD_GATEWAY
  30. public static final int HTTP_BAD_METHOD
  31. public static final int HTTP_BAD_REQUEST
  32. public static final int HTTP_CLIENT_TIMEOUT
  33. public static final int HTTP_CONFLICT
  34. public static final int HTTP_CREATED
  35. public static final int HTTP_ENTITY_TOO_LARGE
  36. public static final int HTTP_FORBIDDEN
  37. public static final int HTTP_GATEWAY_TIMEOUT
  38. public static final int HTTP_GONE
  39. public static final int HTTP_INTERNAL_ERROR
  40. public static final int HTTP_LENGTH_REQUIRED
  41. public static final int HTTP_MOVED_PERM
  42. public static final int HTTP_MOVED_TEMP
  43. public static final int HTTP_MULT_CHOICE
  44. public static final int HTTP_NOT_ACCEPTABLE
  45. public static final int HTTP_NOT_AUTHORITATIVE
  46. public static final int HTTP_NOT_FOUND
  47. public static final int HTTP_NOT_IMPLEMENTED
  48. public static final int HTTP_NOT_MODIFIED
  49. public static final int HTTP_NO_CONTENT
  50. public static final int HTTP_OK
  51. public static final int HTTP_PARTIAL
  52. public static final int HTTP_PAYMENT_REQUIRED
  53. public static final int HTTP_PRECON_FAILED
  54. public static final int HTTP_PROXY_AUTH
  55. public static final int HTTP_REQ_TOO_LONG
  56. public static final int HTTP_RESET
  57. public static final int HTTP_SEE_OTHER
  58. public static final int HTTP_SERVER_ERROR
  59. public static final int HTTP_UNAUTHORIZED
  60. public static final int HTTP_UNAVAILABLE
  61. public static final int HTTP_UNSUPPORTED_TYPE
  62. public static final int HTTP_USE_PROXY
  63. 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.

Читайте также:  Tor browser для андроид как установить

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.

  1. Create a URL instance.
  2. Open url connection and cast it to HttpURLConnection.
  3. 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
  4. If request method is GET, then use below code to open input stream and read server response data.
  5. 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.
  6. 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
Known Direct Subclasses

Class Overview

An 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:

  1. Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection .
  2. Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
  3. Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by getOutputStream() .
  4. Read the response. Response headers typically include metadata such as the response body’s content type and length, modified dates and session cookies. The response body may be read from the stream returned by getInputStream() . If the response has no body, that method returns an empty stream.
  5. Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect() . Disconnecting releases the resources held by a connection so they may be closed or reused.

For example, to retrieve the webpage at http://www.android.com/ :

Secure Communication with HTTPS

Response Handling

If 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 Content

For 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:

Performance

When 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-On

HTTP Authentication

Sessions with Cookies

The 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 Methods

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) .

Proxies

IPv6 Support

This 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 Caching

Avoiding Bugs In Earlier Releases

Each instance of HttpURLConnection may be used for one request/response pair. Instances of this class are not thread safe.

Summary

Constants
int HTTP_ACCEPTED Numeric status code, 202: Accepted
int HTTP_BAD_GATEWAY Numeric status code, 502: Bad Gateway
int HTTP_BAD_METHOD Numeric status code, 405: Bad Method
int HTTP_BAD_REQUEST Numeric status code, 400: Bad Request
int HTTP_CLIENT_TIMEOUT Numeric status code, 408: Client Timeout
int HTTP_CONFLICT Numeric status code, 409: Conflict
int HTTP_CREATED Numeric status code, 201: Created
int HTTP_ENTITY_TOO_LARGE Numeric status code, 413: Entity too large
int HTTP_FORBIDDEN Numeric status code, 403: Forbidden
int HTTP_GATEWAY_TIMEOUT Numeric status code, 504: Gateway timeout
int HTTP_GONE Numeric status code, 410: Gone
int HTTP_INTERNAL_ERROR Numeric status code, 500: Internal error
int HTTP_LENGTH_REQUIRED Numeric status code, 411: Length required
int HTTP_MOVED_PERM Numeric status code, 301 Moved permanently
int HTTP_MOVED_TEMP Numeric status code, 302: Moved temporarily
int HTTP_MULT_CHOICE Numeric status code, 300: Multiple choices
int HTTP_NOT_ACCEPTABLE Numeric status code, 406: Not acceptable
int HTTP_NOT_AUTHORITATIVE Numeric status code, 203: Not authoritative
int HTTP_NOT_FOUND Numeric status code, 404: Not found
int HTTP_NOT_IMPLEMENTED Numeric status code, 501: Not implemented
int HTTP_NOT_MODIFIED Numeric status code, 304: Not modified
int HTTP_NO_CONTENT Numeric status code, 204: No content
int HTTP_OK Numeric status code, 200: OK
int HTTP_PARTIAL Numeric status code, 206: Partial
int HTTP_PAYMENT_REQUIRED Numeric status code, 402: Payment required
int HTTP_PRECON_FAILED Numeric status code, 412: Precondition failed
int HTTP_PROXY_AUTH Numeric status code, 407: Proxy authentication required
int HTTP_REQ_TOO_LONG Numeric status code, 414: Request too long
int HTTP_RESET Numeric status code, 205: Reset
int HTTP_SEE_OTHER Numeric status code, 303: See other
int HTTP_SERVER_ERROR This constant was deprecated in API level 1. Use HTTP_INTERNAL_ERROR instead.
int HTTP_UNAUTHORIZED Numeric status code, 401: Unauthorized
int HTTP_UNAVAILABLE Numeric status code, 503: Unavailable
int HTTP_UNSUPPORTED_TYPE Numeric status code, 415: Unsupported type
int HTTP_USE_PROXY Numeric status code, 305: Use proxy.
int HTTP_VERSION Numeric status code, 505: Version not supported
Fields
chunkLength If the HTTP chunked encoding is enabled this parameter defines the chunk-length.
fixedContentLength The byte count in the request body if it is both known and streamed; and -1 otherwise.
fixedContentLengthLong The byte count in the request body if it is both known and streamed; and -1 otherwise.
instanceFollowRedirects Flag to define whether the protocol will automatically follow redirects or not.
method The HTTP request method of this HttpURLConnection .
responseCode The status code of the response obtained from the HTTP request.
responseMessage The HTTP response message which corresponds to the response code.
[Expand]
allowUserInteraction Unused by Android.
connected Specifies whether this URLConnection is already connected to the remote resource.
doInput Specifies whether this URLConnection allows receiving data.
doOutput Specifies whether this URLConnection allows sending data.
ifModifiedSince The data must be modified more recently than this time in milliseconds since January 1, 1970, GMT to be transmitted.
url The URL which represents the remote target of this URLConnection .
useCaches Specifies whether the using of caches is enabled or the data has to be recent for every request.

Constants

public static final int HTTP_ACCEPTED

Numeric status code, 202: Accepted

public static final int HTTP_BAD_GATEWAY

Numeric status code, 502: Bad Gateway

public static final int HTTP_BAD_METHOD

Numeric status code, 405: Bad Method

public static final int HTTP_BAD_REQUEST

Numeric status code, 400: Bad Request

public static final int HTTP_CLIENT_TIMEOUT

Numeric status code, 408: Client Timeout

public static final int HTTP_CONFLICT

Numeric status code, 409: Conflict

public static final int HTTP_CREATED

Numeric status code, 201: Created

public static final int HTTP_ENTITY_TOO_LARGE

Numeric status code, 413: Entity too large

public static final int HTTP_FORBIDDEN

Numeric status code, 403: Forbidden

public static final int HTTP_GATEWAY_TIMEOUT

Numeric status code, 504: Gateway timeout

public static final int HTTP_GONE

Numeric status code, 410: Gone

public static final int HTTP_INTERNAL_ERROR

Numeric status code, 500: Internal error

public static final int HTTP_LENGTH_REQUIRED

Numeric status code, 411: Length required

public static final int HTTP_MOVED_PERM

Numeric status code, 301 Moved permanently

public static final int HTTP_MOVED_TEMP

Numeric status code, 302: Moved temporarily

public static final int HTTP_MULT_CHOICE

Numeric status code, 300: Multiple choices

public static final int HTTP_NOT_ACCEPTABLE

Numeric status code, 406: Not acceptable

public static final int HTTP_NOT_AUTHORITATIVE

Numeric status code, 203: Not authoritative

public static final int HTTP_NOT_FOUND

Numeric status code, 404: Not found

public static final int HTTP_NOT_IMPLEMENTED

Numeric status code, 501: Not implemented

public static final int HTTP_NOT_MODIFIED

Numeric status code, 304: Not modified

public static final int HTTP_NO_CONTENT

Numeric status code, 204: No content

public static final int HTTP_OK

Numeric status code, 200: OK

public static final int HTTP_PARTIAL

Numeric status code, 206: Partial

public static final int HTTP_PAYMENT_REQUIRED

Numeric status code, 402: Payment required

public static final int HTTP_PRECON_FAILED

Numeric status code, 412: Precondition failed

public static final int HTTP_PROXY_AUTH

Numeric status code, 407: Proxy authentication required

public static final int HTTP_REQ_TOO_LONG

Numeric status code, 414: Request too long

public static final int HTTP_RESET

Numeric status code, 205: Reset

public static final int HTTP_SEE_OTHER

Numeric status code, 303: See other

public static final int HTTP_SERVER_ERROR

This constant was deprecated in API level 1.
Use HTTP_INTERNAL_ERROR instead.

Numeric status code, 500: Internal error

public static final int HTTP_UNAUTHORIZED

Numeric status code, 401: Unauthorized

public static final int HTTP_UNAVAILABLE

Numeric status code, 503: Unavailable

public static final int HTTP_UNSUPPORTED_TYPE

Numeric status code, 415: Unsupported type

public static final int HTTP_USE_PROXY

Numeric status code, 305: Use proxy.

Like Firefox and Chrome, this class doesn’t honor this response code. Other implementations respond to this status code by retrying the request using the HTTP proxy named by the response’s Location header field.

public static final int HTTP_VERSION

Numeric status code, 505: Version not supported

Источник

Читайте также:  Samsung sm t805 android
Оцените статью