Передача данных в android методом post. HttpURLConnection: Подключаемся к URL

Передача данных в android методом post. HttpURLConnection: Подключаемся к URL

22.02.2019

Полный текст статьи и исходники программы доступны только зарегистрированным участникам сайта.

Стоимость регистрации - символические 340 рублей.

Для регистрации сначала необходимо пополнить Яндекс.Кошелек на указанную сумму (или Webmoney-кошелек R390884954122 или QIWI - 9055113963 (кошелек, не на счёт телефона!)), а затем прислать письмо на адрес [email protected] с указанием, на какой кошелек вы делали оплату и реквизиты, по которым можно вас определить (не прикрепляйте к письму картинки или файлы). Учитывайте комиссию при переводах.

Не присылайте в письме мои номера кошельков - поверьте, я их знаю и без вас.

В ответном письме вы получите учётные данные для чтения статей из закрытой зоны за второй курс.

Доступ к третьему курсу обучения доступен только после оплаты второго курса и составляет 340 руб.

Доступ к чётвертому курсу обучения доступен после оплаты третьего курса и составляет 340 руб. и т.д.

При оплате сразу всех курсов одновременно (2-9) цена составит 2700 руб.

Доступ даётся как минимум на один год. Для тех, кто оплатил третий и другие курсы, сроки доступа увеличиваются.

Знакомство с классом HttpURLConnection

Для соединения с веб-серверами Android предлагает несколько способов взаимодействия. В новых проектах для современных устройств рекомендуется использовать класс HttpURLConnection , который мы с вами рассмотрим на примерах.

Класс java.net.HttpURLConnection является подклассом java.net.URLConnection и позволяет реализовать работу по отправке и получении данных из сети по протоколу HTTP. Данные могут быть любого типа и длины. Данный класс следует использовать для отправки и получения потоковых данных, размеры которых нельзя заранее определить. Используя данный класс, вам не нужно думать о сокетах и реализовывать собственные способы общения между клиентом и сервером.

Алгоритм использования следующий:

  • Получить объект HttpURLConnection через вызов URL.openConnection() и привести результат к HttpURLConnection
  • Подготовить необходимый запрос. Основное в запросе - сам сетевой адрес. Также в запросе можно указать различные метаданные: учётные данные, тип контента, куки сессии и т.п.
  • Опционально загрузить тело запроса. В этом случае используется метод setDoOutput(true) . Передача данных, записанных в поток, возвращается через метод getOutputStream()
  • Прочитать ответ. Заголовок ответа обычно включает метаданные, такие как тип и длина контента, даты изменения, куки сессии. Прочитать данные из потока можно через метод getInputStream() . Если у ответа нет тела, то метод возвращает пустой поток.
  • Разорвать соединение. После прочтения ответа от сервера HttpURLConnection следует закрыть через вызов метода disconnect() . Тем самым вы освобождаете ресурсы, занимаемые соединением.

Например, для получения страницы по адресу http://сайт/android/ можно использовать такой код:

URL url = new URL("http://сайт/android/"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); readStream(in); finally { urlConnection.disconnect(); } }

По умолчанию HttpURLConnection использует метод GET . Для использования POST вызывайте setDoOutput(true) и посылайте данные через openOutputStream() . Другие HTTP-методы (OPTIONS, HEAD, PUT, DELETE and TRACE) настраиваются через метод setRequestMethod(String) .

Для работы через прокси-сервер используйте URL.openConnection(Proxy) при создании соединения.

Каждый экземпляр HttpURLConnection может использоваться только для одной пары запроса/ответа. Операции с соединениями следует проводить в отдельном потоке.

Вы вошли на сайт, как гость.
, чтобы прочитать статью

At a high level, you use Volley by creating a RequestQueue and passing it Request objects. The RequestQueue manages worker threads for running the network operations, reading from and writing to the cache, and parsing responses. Requests do the parsing of raw responses and Volley takes care of dispatching the parsed response back to the main thread for delivery.

This lesson describes how to send a request using the Volley.newRequestQueue convenience method, which sets up a RequestQueue for you. See the next lesson, for information on how to set up a RequestQueue yourself.

This lesson also describes how to add a request to a RequestQueue and cancel a request.

Add the INTERNET permission

To use Volley, you must add the permission to your app"s manifest. Without this, your app won"t be able to connect to the network.

Use newRequestQueue

Volley provides a convenience method Volley.newRequestQueue that sets up a RequestQueue for you, using default values, and starts the queue. For example:

Kotlin

val textView = findViewById(R.id.text) // ... // Instantiate the RequestQueue. val queue = Volley.newRequestQueue(this) val url = "http://www.google.com" // Request a string response from the provided URL. val stringRequest = StringRequest(Request.Method.GET, url, Response.Listener { response -> // Display the first 500 characters of the response string. textView.text = "Response is: ${response.substring(0, 500)}" }, Response.ErrorListener { textView.text = "That didn"t work!" }) // Add the request to the RequestQueue. queue.add(stringRequest)

Java

final TextView textView = (TextView) findViewById(R.id.text); // ... // Instantiate the RequestQueue. RequestQueue queue = Volley.newRequestQueue(this); String url ="http://www.google.com"; // Request a string response from the provided URL. StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener() { @Override public void onResponse(String response) { // Display the first 500 characters of the response string. textView.setText("Response is: "+ response.substring(0,500)); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { textView.setText("That didn"t work!"); } }); // Add the request to the RequestQueue. queue.add(stringRequest);

Volley always delivers parsed responses on the main thread. Running on the main thread is convenient for populating UI controls with received data, as you can freely modify UI controls directly from your response handler, but it"s especially critical to many of the important semantics provided by the library, particularly related to canceling requests.

See for a description of how to set up a RequestQueue yourself, instead of using the Volley.newRequestQueue convenience method.

Send a request

To send a request, you simply construct one and add it to the RequestQueue with add() , as shown above. Once you add the request it moves through the pipeline, gets serviced, and has its raw response parsed and delivered.

When you call add() , Volley runs one cache processing thread and a pool of network dispatch threads. When you add a request to the queue, it is picked up by the cache thread and triaged: if the request can be serviced from cache, the cached response is parsed on the cache thread and the parsed response is delivered on the main thread. If the request cannot be serviced from cache, it is placed on the network queue. The first available network thread takes the request from the queue, performs the HTTP transaction, parses the response on the worker thread, writes the response to cache, and posts the parsed response back to the main thread for delivery.

Note that expensive operations like blocking I/O and parsing/decoding are done on worker threads. You can add a request from any thread, but responses are always delivered on the main thread.

Figure 1 illustrates the life of a request:

Figure 1. Life of a request.

Cancel a request

To cancel a request, call cancel() on your Request object. Once cancelled, Volley guarantees that your response handler will never be called. What this means in practice is that you can cancel all of your pending requests in your activity"s method and you don"t have to litter your response handlers with checks for getActivity() == null , whether onSaveInstanceState() has been called already, or other defensive boilerplate.

To take advantage of this behavior, you would typically have to track all in-flight requests in order to be able to cancel them at the appropriate time. There is an easier way: you can associate a tag object with each request. You can then use this tag to provide a scope of requests to cancel. For example, you can tag all of your requests with the they are being made on behalf of, and call requestQueue.cancelAll(this) from . Similarly, you could tag all thumbnail image requests in a tab with their respective tabs and cancel on swipe to make sure that the new tab isn"t being held up by requests from another one.

Here is an example that uses a string value for the tag:

  1. Define your tag and add it to your requests.

    Kotlin

    val TAG = "MyTag" val stringRequest: StringRequest // Assume this exists. val requestQueue: RequestQueue? // Assume this exists. // Set the tag on the request. stringRequest.tag = TAG // Add the request to the RequestQueue. requestQueue?.add(stringRequest)

    Java

    public static final String TAG = "MyTag"; StringRequest stringRequest; // Assume this exists. RequestQueue requestQueue; // Assume this exists. // Set the tag on the request. stringRequest.setTag(TAG); // Add the request to the RequestQueue. requestQueue.add(stringRequest);
  2. In your activity"s method, cancel all requests that have this tag.

    Kotlin

    protected fun onStop() { super.onStop() requestQueue?.cancelAll(TAG) }

    Java

    @Override protected void onStop () { super.onStop(); if (requestQueue != null) { requestQueue.cancelAll(TAG); } }

    Take care when canceling requests. If you are depending on your response handler to advance a state or kick off another process, you need to account for this. Again, the response handler will not be called.

In Android HTTP POST & GET tutorial , I have explained how to send HTTP POST and GET requests programmatically in Android.

We can use org.apache.http.client.HttpClient class to make HTTP requests.

Send HTTP POST request

Follow the steps to send HTTP POST requests.

HttpClient httpClient = new DefaultHttpClient();

2. Create an object of HttpPost

HttpPost httpPost = new HttpPost("http://www.example.com");

3. Add POST parameters

List (2); nameValuePair.add(new BasicNameValuePair("username", "test_user")); nameValuePair.add(new BasicNameValuePair("password", "123456789"));

4. Encode POST data

We need to encode our data into valid URL format before making HTTP request.

//Encoding POST data try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }

5. Finally making an HTTP POST request

Try { HttpResponse response = httpClient.execute(httpPost); // write response to log Log.d("Http Post Response:", response.toString()); } catch (ClientProtocolException e) { // Log exception e.printStackTrace(); } catch (IOException e) { // Log exception e.printStackTrace(); }

Make sure you add Internet permission to your app before making such requests else you might see some errors.

You can add Internet permissions by adding this line to your manifest file above application tag.

Android HTTP POST Example

package com.example.httprequestexample; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class HTTPPostActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); makePostRequest(); } private void makePostRequest() { HttpClient httpClient = new DefaultHttpClient(); // replace with your url HttpPost httpPost = new HttpPost("www.example.com"); //Post Data List nameValuePair = new ArrayList(2); nameValuePair.add(new BasicNameValuePair("username", "test_user")); nameValuePair.add(new BasicNameValuePair("password", "123456789")); //Encoding POST data try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); } catch (UnsupportedEncodingException e) { // log exception e.printStackTrace(); } //making POST request. try { HttpResponse response = httpClient.execute(httpPost); // write response to log Log.d("Http Post Response:", response.toString()); } catch (ClientProtocolException e) { // Log exception e.printStackTrace(); } catch (IOException e) { // Log exception e.printStackTrace(); } } }

Send HTTP GET Request

To send HTTP GET request follow the steps.
1. Create an object of HttpClient

HttpClient client = new DefaultHttpClient();

2. Create an object of HttpGet

HttpGet request = new HttpGet("http://www.example.com");

3. Finally make HTTP request

HttpResponse response; try { response = client.execute(request); Log.d("Response of GET request", response.toString()); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }

Android HTTP GET Example

package com.example.httprequestexample; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class HTTPGETActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); makeGetRequest(); } private void makeGetRequest() { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("http://www.example.com"); // replace with your url HttpResponse response; try { response = client.execute(request); Log.d("Response of GET request", response.toString()); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

© 2024 beasthackerz.ru - Браузеры. Аудио. Жесткий диск. Программы. Локальная сеть. Windows