Android studio httpurlconnection post

Содержание
  1. HttpURLConnection: Android Tutorial
  2. Integrating HttpURLConnection
  3. Full project code and final thoughts
  4. Android HttpURLConnection Example
  5. 1. HttpURLConnection use steps.
  6. 2. HttpURLConnection Examples.
  7. 2.1 Main Activity.
  8. 2.2 Main Layout Xml File.
  9. 2.3 Android Manifest Xml File.
  10. Как отправить POST запрос с помощью HttpURLConnection?
  11. Kotlin Android HttpURLConnection Tutorial and Examples
  12. What is HttpUrlConnection?
  13. Quick HttpURLConnection Examples
  14. Android HttpURLConection – HTTP GET in Java
  15. Quick HTTP GET Examples
  16. 1. How to perform HTTP GET and return a JSONObject
  17. 2. How to perform a HTTP GET and return a BufferedInputStream
  18. Android HttpURLConection -HTTP POST
  19. Quick HttpURLConnection HowTo Examples
  20. 1. How to make a HttpURLConection HTTP POST Request and Return a response
  21. 2. How to make a HttpURLConection HTTP POST Request with Authentication
  22. Full Example: How to Insert/Save into MySQL Database from Android via HttpURLConnection POST
  23. Video Tutorial(ProgrammingWizards TV Channel)
  24. Full Code
  25. 3. Our Layouts
  26. 4. AndroidManifest.xml
  27. 5. Download
  28. Kotlin Android JSON with HttpURLConnection – Easiest Examples
  29. What is AsyncTask?
  30. What is HttpURLConnection?
  31. What is a GridView?
  32. Project Structure
  33. AndroidManifest.xml
  34. row_model.xml
  35. activity_main.xml
  36. JSONDownloader.kt
  37. Derive From AsyncTask
  38. Show ProgressDialog
  39. Connect to Network via HttpURLConnection
  40. Download JSON Data
  41. JSONParser.kt
  42. MainActivity.kt
  43. Result
  44. Example 2 : Kotlin Android – JSON ListView – HTTP GET using HttURLConnection
  45. Sample JSON

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!

Источник

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.

Источник

Как отправить POST запрос с помощью HttpURLConnection?

Добрый вечер. Начал разбираться в программировании под android и нашел много поднобных инструкций по отправке POST запроса на php сервер с помощью HttpClient, но потом выяснил что он устарел и перестал поддерживаться последим SDK который у меня установлен.

Читайте также:  Перевод сервисного меню андроид

После чего узнал что следует пользоваться HttpURLConnection, но информации о том как осуществить с помощью него POST или GET запросы и обработать ответ от сервера не нашел.

Надеюсь на вашу помощь, желательно с подробными примерами. Огромное спасибо.

  • Вопрос задан более трёх лет назад
  • 36845 просмотров

Оценить 2 комментария

Минимум как-то так. А там сами обработаете что и как требуется и положено.

Особого отличия от HttpClient нет.

По сути нужно заполнить OutputStream дополнительно к текстовым параметрам формы еще и бинарными данными.
Вот какой-то пример есть: Upload a file using HTTPUrlConnection.

Рекомендую сначала настроить свой php и убедиться, что все работает при отправке файла через HTML-форму. Потом уже пробовать свой java-клиент. Для начала пробуйте мелкие бинарники передавать.
Смотрите, чтобы сервер ваш не согласился на прием файла очень большого размера, который ему просто некуда будет сохранить, т.е. нужно ограничение по размеру принимаемого файла. Или прием данных нежелательного содержания, например, какой-либо исполняемый код. Ну, это уже все другие вопросы.

Для отладки выводите лог и обрабатывайте ошибки буквально после каждого действия на клиенте и на сервере.

Источник

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 remove device and

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.

Источник

Оцените статью