Android httpurlconnection post json

Содержание
  1. Выполнение запроса JSON POST с помощью HttpURLConnection
  2. 1. Обзор
  3. Дальнейшее чтение:
  4. Сделайте простой HTTP-запрос на Java
  5. Аутентификация с помощью HttpURLConnection
  6. Подключение через Прокси-серверы в ядре Java
  7. 2. Создание запроса JSON POST с помощью HttpURLConnection
  8. 2.1. Создайте объект URL
  9. 2.2. Откройте соединение
  10. 2.3. Установите метод запроса
  11. 2.4. Установите параметр заголовка типа содержимого запроса
  12. 2.5. Установите Тип Формата Ответа
  13. 2.6. Убедитесь, что Соединение Будет Использоваться для Отправки Контента
  14. 2.7. Создайте тело запроса
  15. 2.8. Считывание Ответа Из Входного Потока
  16. 3. Заключение
  17. Android | Send JSON Content to the Cloud Using HttpUrlConnection & Kotlin Coroutine
  18. Objectives
  19. Environment, Tools & Library
  20. About the app
  21. ( 1 ) Create new Android Project
  22. ( 2 ) Add Permissions
  23. ( 3 ) Design App Layout
  24. ( 4 ) Send JSON to Server
  25. Kotlin Android HttpURLConnection Tutorial and Examples
  26. What is HttpUrlConnection?
  27. Quick HttpURLConnection Examples
  28. Android HttpURLConection – HTTP GET in Java
  29. Quick HTTP GET Examples
  30. 1. How to perform HTTP GET and return a JSONObject
  31. 2. How to perform a HTTP GET and return a BufferedInputStream
  32. Android HttpURLConection -HTTP POST
  33. Quick HttpURLConnection HowTo Examples
  34. 1. How to make a HttpURLConection HTTP POST Request and Return a response
  35. 2. How to make a HttpURLConection HTTP POST Request with Authentication
  36. Full Example: How to Insert/Save into MySQL Database from Android via HttpURLConnection POST
  37. Video Tutorial(ProgrammingWizards TV Channel)
  38. Full Code
  39. 3. Our Layouts
  40. 4. AndroidManifest.xml
  41. 5. Download
  42. Kotlin Android JSON with HttpURLConnection – Easiest Examples
  43. What is AsyncTask?
  44. What is HttpURLConnection?
  45. What is a GridView?
  46. Project Structure
  47. AndroidManifest.xml
  48. row_model.xml
  49. activity_main.xml
  50. JSONDownloader.kt
  51. Derive From AsyncTask
  52. Show ProgressDialog
  53. Connect to Network via HttpURLConnection
  54. Download JSON Data
  55. JSONParser.kt
  56. MainActivity.kt
  57. Result
  58. Example 2 : Kotlin Android – JSON ListView – HTTP GET using HttURLConnection
  59. Sample JSON

Выполнение запроса JSON POST с помощью HttpURLConnection

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

Автор: baeldung
Дата записи

1. Обзор

В этом уроке мы продемонстрируем, как сделать запрос JSON POST с помощью HttpURLConnection .

Дальнейшее чтение:

Сделайте простой HTTP-запрос на Java

Аутентификация с помощью HttpURLConnection

Подключение через Прокси-серверы в ядре Java

2. Создание запроса JSON POST с помощью HttpURLConnection

2.1. Создайте объект URL

Давайте создадим объект URL с целевой строкой URI, которая принимает данные JSON с помощью метода HTTP POST:

2.2. Откройте соединение

Из приведенного выше объекта URL мы можем вызвать метод open Connection , чтобы получить объект HttpURLConnection|/.

Мы не можем создать экземпляр HttpURLConnection напрямую, так как это абстрактный класс:

2.3. Установите метод запроса

Чтобы отправить запрос на публикацию, мы должны установить свойство метода запроса на ПУБЛИКАЦИЮ:

2.4. Установите параметр заголовка типа содержимого запроса

Установите “content-type” заголовок запроса в “application/json” , чтобы отправить содержимое запроса в форме JSON. Этот параметр должен быть установлен для отправки тела запроса в формате JSON.

В противном случае сервер возвращает код состояния HTTP “400-плохой запрос”:

Кроме того, обратите внимание, что мы упомянули кодировку кодировки вместе с типом контента. Это полезно, если кодировка содержимого запроса отличается от кодировки UTF-8, которая является кодировкой по умолчанию.

2.5. Установите Тип Формата Ответа

Установите “Принять” заголовок запроса на “приложение/json” чтобы прочитать ответ в нужном формате:

2.6. Убедитесь, что Соединение Будет Использоваться для Отправки Контента

Чтобы отправить содержимое запроса, давайте включим свойство URLConnection объекта do Output в true .

В противном случае мы не сможем записывать содержимое в выходной поток подключения:

2.7. Создайте тело запроса

После создания пользовательской строки JSON:

Нам нужно было бы написать его:

2.8. Считывание Ответа Из Входного Потока

Получите входной поток для чтения содержимого ответа. Не забудьте использовать try-with-resources, чтобы автоматически закрыть поток ответов.

Прочитайте все содержимое ответа и распечатайте окончательную строку ответа:

Если ответ в формате JSON, используйте любые сторонние анализаторы JSON, такие как библиотека Джексона , Gson или org.json, для анализа ответа.

3. Заключение

В этой статье мы узнали, как сделать запрос POST с телом содержимого JSON с помощью HttpURLConnection .

Как всегда, соответствующие фрагменты кода можно найти на GitHub

Источник

Android | Send JSON Content to the Cloud Using HttpUrlConnection & Kotlin Coroutine

Sending data to the cloud is a common task in mobile applications. Here we will consume an open REST service to practice sending data in JSON format to a cloud server. We will use HttpURLConnection to make an HTTP POST request to the server. Then, we can verify that our request is successful by going to hmkcode-api.appspot.com/links.html page.

Objectives

  1. How to send HTTP POST request to the cloud with JSON content.
  2. How to check network connection?
  3. How to use kotlin coroutine to perform network operations on a separate thread?

Environment, Tools & Library

used in this post

  • Android Studio 3.5.1
  • HttpURLConnection client.
  • REST service http://hmkcode-api.appspot.com/rest/link/add to post data.
  • https://hmkcode-api.appspot.com/links.html to view our stored data.

About the app

We are going to build a sample app that stores links info in the cloud. The app takes three inputs from the user link title, url and optional tags. When the user click send, the app will build a JSON object holding the three inputs, add the built JSON object to the POST request body and finally execute the POST request.

( 1 ) Create new Android Project

Create new android application keep default options.

  • Application Name: post-json
  • Package Name: com.hmkcode
  • Language: Kotlin
  • Minimum SDK: API 19: Android 4.4 (KitKat)

( 2 ) Add Permissions

  • Add the following two lines to the AndroidMainifest.xml file

( 3 ) Design App Layout

  • Add the following views to activity_main.xml .
  • TextView for displaying network connection info.
  • Three EditText for title, URL & tags account.

activity_main.xml

Dependencies
  • You need to include the following dependencies to build.gradle

build.gradle (Module: post-json)

( 4 ) Send JSON to Server

MainActivity.kt is the only class where we need to code the following:

  • a. Check network connectivity.
  • b. Build httpPost() function with IO dispatcher.
  • c. Build send() function to launch httpPost() in lifecycleScope coroutine scope.

Источник

Kotlin Android HttpURLConnection Tutorial and Examples

In this piece we explore HttpURLConnection, android and java’s standard networking class.

As a networking class HttpURLConnection can be to make HTTP requests over the web.

What is HttpUrlConnection?

HttpUrlconnection is a UrlConnection for HTTP used to send as well receive data over the web. These data may be of any type and length.

HttpURLConnection was added in android 1.0 and is a URLConnection with support for HTTP-specific features.
Like its parent URLConnection, it resides in the java.net package. This class allows us do networking easily and is the standard networking library in android.

  • HttpURLConnection subclasses java.net.URLConnection.
  • It also directly Superclasses HttpsURLConnection
Читайте также:  Что такое встряхивание андроид

HttpUrlConnection can also be used to send and receive streams whose length isn’t known in advance.

To be used,we obtain a new HttpUrlconnection object by calling url.openConnection() and casting to HttpUrlConnection .

If we open a connction to a url with «https» scheme,this returns HttpsUrlConnection.

Here is a simple usage of HttpURLConnection to download a webpage:

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

Posting Content

To post some content to a web server, first you have to configure the connection for output using setDoOutput(true).

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.

HTTP Authentication

HttpURLConnection supports HTTP basic authentication. You can use Authenticator to set the VM-wide authentication handler:

Sessions with Cookies

To establish and maintain a potentially long-lived session between client and server, HttpURLConnection includes an extensible cookie manager. Enable VM-wide cookie management using CookieHandler and CookieManager:

Quick HttpURLConnection Examples

1. Get Byte Array From Server

The aim is to get a byte array when supplied a URL string. We first instantiate the java.net.URL with the url.

Once we have the java.net.URL instance, we use it to open a connection which returns us a URLConnection .

This URLConnection is the parent class of HttpURLConnection , so we just cast it to our HttpUrlConnection.

Here’s the full method:

2. Ping URL

This method will ping the given url for availability. It will send a HEAD request and return true if the response code is in the 200 — 399 range.

3. Download Image Using HttpURLConnection

There are many complex image downloaders and loaders out there. But we also have to know how to implement our own with basic HttpURLConnection and AsyncTask

Here’s how we can download a bitmap and return it. To use with AsyncTask all you have to do is call this method inside your doInBackground() method, then receive the bitmap in the onPostExecute() method, where then you can render it into your imageview.

4. Two methods to get Domain Names

You can reuse these two methods to get domain name for either SSL sites and Non-SSL sites.

All you have to do is pass the string url.

5. How to get Protocol when provided a url
6. How to Check if a given URL can respond to a HTTP request

This method will Check if a URL exists and can respond to an HTTP request.

The first parameter is the url to check. Then we return True if the URL exists, false if it doesn’t or an error occured.

7. How to get ContentTypes(and Cache them)

We want to see how we can get Content Types. We will be caching our results throughout the runtime of our app.

Start by importing HttpURLConnection, URL, and HashMap.

The HttpURLConnection is of course our networking class. The URL will allow us convert a simple string into a URL we can actually connect.

The HashMap will be used to cache our content types.

Let’s start by creating a class:

You can see we have used the final modifier. This keyword is a non-access modifier applicable only to a variable, a method or a class.

A final class is a class that can’t be extended or derived from. This is a utility class and we don’t want it extended.

We will then have two constants:

The TIMEOUT_DIRECT is our default timeout for direct URL connections. On the other hand cachedContentTypes will cache our retrieved content types.

Now we will have two methods responsible for getting us the content types.

First we are receiving a URL object. We will check first if that URL is already contained in our cached contents. If it is then we just get it from there. Otherwise we open our connection, set it’s properties and return later our content type.

Then our second method simply receives a string then we build our URL from that string. Then we can simply reuse the first method.

Just take those two methods and our two constants and add them to our class.

Android HttpURLConection – HTTP GET in Java

Android HttpURLConnection HTTP GET Tutorial.

In this piece we explore some HTTP GET examples. Basicaly how to perform HTTP GET using the HttpURLConnection class.

Quick HTTP GET Examples

Let’s start by looking at some quick HTTP GET examples.

1. How to perform HTTP GET and return a JSONObject

The first step is to perform a HTTP GET when provided the target URL and a Context object.

2. How to perform a HTTP GET and return a BufferedInputStream

Let’s say we have a getUserAgentString() method as follows:

Then here’s we get the and return the BufferedInputStream.

Android HttpURLConection -HTTP POST

Android HttpURLConnection HTTP POST Tutorial.

This section contains various examples that allow you make HTTP POST request against a server. We use android’s standard networking class HttpURLConection to make our requests.

Quick HttpURLConnection HowTo Examples

Let’s start by looking at some HowTo examples.

1. How to make a HttpURLConection HTTP POST Request and Return a response

Let’s say we we provide you with a URL encoded string data. You are supposed to send them via a HTTP POST Request using HttpURLConnection.

Here’s how we can do it.

2. How to make a HttpURLConection HTTP POST Request with Authentication

We want to make this post request in a background thread using AsyncTask class. We make that POST Request and receive a result.

Say for instance we want to make the POST request to GitHub.

Our first step would be to create a class that would then represent our result, lets call the class HTTPConnectionResult .

Our result will contain a string and a response code.

Then let’s another class to represent User session data. This class will store data associated with a given user session, or the time the request was being made.

Читайте также:  Как удалить все ммс с андроида

Those data for us will comprise the id, credentials, token and login.

What about a last class before looking at our AsyncTask, in this case a Util class:

Then now we come tou our AsynTask class.

Here’s the thing, this class will perform an authentication to our Github account for instance. We will make a HTTP POST request for this and receive a result.

We have to do this in a background thread to avoid freezing the user interface.

The request itself we perform it in the doInBackground method. The result of this method will be our UserSessionData object.

Then when the results are back they will automatically get passed to our onPostExecute() method.

From there we can receive those data and store them in SharedPreferences. This allows our app to remember login details.

Here’s the code for that.

NB/= This is not a standalone example, and is meant to be incorporated into your own project.

2. How to make a HTTP GET Request

We’ve seen how to make a HTTP POST request, in the first part. Let’s now continue and create another async task class that will this time perform a HTTP GET request.

Let’s now say we want to download a GitHub Readme.

But first we have to establishe a connection for making a HTTP GET request.

We just use the openConnection() method of the URL class and make sure to our request method as GET :

Then we get our authentication token from our SharedPreferences and set it as the request property, with the key being Authorization while the value being that token:

The actual download, we said, will have to be performed in a background thread. This allows the UI to remain responsive.

Full Example: How to Insert/Save into MySQL Database from Android via HttpURLConnection POST

Android MySQL Insert tutorial.In this tutorial,we look at Android MySQL database,saving data to MySQL. We insert data from edittexts into mysql.

Alot of mobile applications employ webservice to enrich their functionalities and capabilities.

Even though mobile devices are at their most powerful currently, they are still not comparable to servers. Servers understandably:

  • Have more memory.
  • Have more processing power.
  • Have more hard drives.

This then makes it imperatvie that delegate some jobs or storage services to the servers.

The most popular server side prgramming language is PHP. While the most popular Relational Database Management System(RDBMS) is MySQL. Combine those with Android the most popular mobile OS, then we have three technologies to build powerful mobile apps.

This tutorial is a start. We want to see how to connect to MySQL database from our android application via PHP. We’ll save data to the database from our app.

PHP and Java will communicate via JSON data exchange format. We’ll make use HTTPURLConnection to make webservice calls.

Let’s go.

  • We use HttpURLConnection class. It will be our HTTP Client
  • We save to MySQL via PHP Code. PHP will be our server side language while mysql our database.
  • We are making a HTTP POST Request. Basically we are sending data to our server.
  • We write through an outputstream,but also read a response from server via inputstream.
  • We do these in background thread using asynctask.

We are using Java programming language.

Video Tutorial(ProgrammingWizards TV Channel)

Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel.

Basically we have a TV for programming where do daily tutorials especially android.

Full Code

In this tutorial we want to see how save or insert data from an edittext to mysql database.

We are using httpurlconnection as our http client. The user will type data then click send to send the data via HTTP.

Our server side language is PHP while our database is mysql.

MySQL table Structure

Here’s our mysql table:

1. PHP Code

Here’s our php code:

2. Java Code.

Android apps can be mainly written in Java or Kotlin. These days however there are many frameworks like Flutter also which use languages like Dart.

In this class we are using Java programming language.

We will have these classes in our project.

(a). Our Spacecraft Class

This is our data object representing a single spacecraft.

(b). Our DataPackager Class
  • Basically,we package our data here for sending.
  • First we add them to a JSON Object.
  • Then we encode them into UTF-8 format using URLEncorder class.
  • Then we return it as a string ready to be written over the network.
(c). Our Connector Class
(d). Our Sender Class
  • Yes,its our Sender class.To send us our data.
  • We send our data in a background thread using AsyncTask,the super class of this sender class.
  • While sending data in background,we show our Progressdialog,starting it in onPreExcecute() and dismissing immediately onPostExecute() is called.
  • We establish an outputStream,write to it using OutputStreamWriter().
  • The OutputStreamWriter() instance,we pass to BufferedWriter() instance.
  • The bufferedWriter() instance writes our data.
  • We then read the server response using bufferedreader instance.
(d). Our MainActivity
  • Launcher activity.
  • Initialize UI like EditTexts.
  • Starts the sender Asynctask on button click,passing on urladdress and edittext.

3. Our Layouts

(a). activity_main.xml

This layout will get inflated into the main activity’s user interface. This will happen via the Activity’s setContentView() method which will require us to pass it the layout.

We will do so inside the onCreate() method of Activity.

content_main.xml

4. AndroidManifest.xml

Remember to add permission for internet in your manifest file.

5. Download

Hey,everything is in source code reference that is well commented and easy to understand and can be downloaded below.

Also check our video tutorial it’s more detailed and explained in step by step.

No. Location Link
1. GitHub Direct Download
2. GitHub Browse
3. YouTube Video Tutorial

Kotlin Android JSON with HttpURLConnection – Easiest Examples

Kotlin is a statically typed programming language that runs on the Java virtual machine and also can be compiled to JavaScript source code or use the LLVM compiler infrastructure.

Kotlin can do anything Java can including creating android apps. And in fact in this class we create an android app that downloads JSON data when a button is clicked, parses that data and renders the result in a custom gridview.

Watch our video tutorial here:

What is AsyncTask?

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

We use AsyncTask in this class instead of raw threads. We will be downloading data in the background thread. Also we parse data in the background thread. AsyncTask will allow us do these while reporting progress using Progress Dialog.

What is HttpURLConnection?

HttpURLConnection is a URLConnection with support for HTTP-specific features. Through this class we will open a connection to a URL pointing us to JSON data and download that data.

We are basically making a HTTP GET request.

What is a GridView?

A gridview is a view that shows items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.

In this class we want to see how to make a HTTP GET request in Kotlin Android using the standard HttpURLConnection class, download some JSON data, parse that data and bind to a custom gridview.

We use AsyncTask for threading, JSONObject and JSONArray for threading.

Project Structure

Here’s our project structure:

AndroidManifest.xml

Let’s add our internet connectivity permission in our androidmanifest. This is needed because we will be connecting to internet to download JSON data.

row_model.xml

This is our row or grid model so to speak. This layout will get inflated into a single grid item in our GridView.

We are working with a custom gridview so that’s why create a custom layout. This layout will contain an ImageView and several textviews.

The ImageView will display a static image while the TextViews will be populated with data parsed from json.

Take note that at the root of our XML we have a CardView with custom cardCornerRadius and cardElevation.

activity_main.xml

This is our main activity layout. It will be inflated into our MainActivity layout.

We will have a LinearLayout at the root with a vertical orientation. This means that it will arrange its children vertically.

We also have a header TextView to display the header of our app, a GridView to render our data parsed from JSON and a button that when clicked initiates the download of the json data from the internet.

JSONDownloader.kt

This is our class responsible for downloading JSON data in the background thread via AsyncTask. We make our HTTP GET request using HttpURLConnection.

We are showing a progress dialog as our data downloads.

Derive From AsyncTask

So as to use AsyncTask which we said abstracts for us away thread details, we have to make our class extend the AsyncTask class which resides in the android.os package. We do this because AsyncTask is an abstract class and requires us to override he doInBackground() method:

But we will be passing some variables via the constructor, here’s how we do that in Kotlin:

As you can see we are passing a Context object, a url leading us to our JSON download url and a GridView wehere we will bind our data.

Show ProgressDialog

We will be showing the progressDialog as our data downloads, however be aware that the ProgressDialog class is deprecated so you may use a progressbar if you like. However, we can still use ProgressBar currently and suppress the deprecation notices.

Connect to Network via HttpURLConnection

Instead of using third part libraries, we will use the standard HttpURLConnection class to connect to our network.

First we instantiate the java.net.URL class passing in our url string.
We then open the a connection to that url using the openConnection() method of URL class and cast the returned URLConnection object to a HttpURLConnection.

We will be making a HTTP GET request. WE also set the connectTimeout , readTimeout and doInput properties. The we return the HttpURLConnection object.

Download JSON Data

We will now download the data given that we’ve established the connection. We first obtain an InputStream from our HttpURLConnection object and pass it to our BufferedInputStream constructor.

We then pass the BufferedInputStream object to an InputStreamReader object, which in turn we pass to our BufferedReader .

We instantiate a StringBuffer(or you can use a StringBuilder) onto which we will append our data.

Here’s the full source code for this JSONDownloader Kotlin class.

JSONParser.kt

This class is responsible for parsing the downloaded JSON data and rendering it into a GridView. We do this in a background thread using AsyncTask.

We show a progress dialog as our data is parsed. We use the native JSONObject and JSONArray classes to parse the data.

We also define ouf data object, which is User as an inner class here. The User class will define a single user.

Furthermore we define pur CustomAdapter class right here. The CustomAdapter will inflate our custom row_model.xml into a View object and bind our data to the custom views.

MainActivity.kt

Our MainActivity Kotlin class. Derives from AppCompatActivity .

We define the URL to our JSON data right here. Furthermmore when the download button is clicked, we instantiate our JSONDownloader class and execute it to start downloading our data.

Result

Kotlin Android GridView HttpURLConnection

Kotlin Android GridView HttpURLConnection

Example 2 : Kotlin Android – JSON ListView – HTTP GET using HttURLConnection

In this class we want to see how to perform a HTTP GET request and fetch data from online and bind to our custom listview. We are using the standard HttpURLConnection class to perform this request.

We also use an AsyncTask to do these in the background thread. We show a progress dialog as our data downloads.

When the download of json data is complete, we parse that data asynchronously using the JSONObject and JSONArray classes. This parsing also takes place in the background thread via AsyncTask.

Sample JSON

We will be using sample JSON from this website.

Источник

Читайте также:  Sdk version android как узнать
Оцените статью