Http post from android app

Android OkHttp3 Http Get Post Request Example

This example will show you how to use OkHttp3 to send get or post HTTP request to a web server and how to parse and display response text in an Android TextView.

1. OKHttp Characters.

  1. OkHttp3 is a third-party open-source library that is contributed by the square company. It has below characters.
  2. User-friendly API.
  3. Support http2, sharing the same socket for all requests from a machine.
  4. Built-in connection pool, support for connection reuse, and reduction of delay.
  5. Supports transparent gzip compression response.
  6. Avoid duplicate requests by caching.
  7. Automatically retry the host’s other IP and redirect automatically when the request fails.

2. Add OkHttp3 Library In build.gradle.

  1. Before you can use the OkHttp3 library, you need to add dependencies in the build.gradle file in android studio as below.
  2. You can get the most recent build library from https://github.com/square/okhttp.
  3. After adding the below code, you need to click the Sync Now link in the top right corner to sync the project.

2. Use OkHttp3 To Create HTTP Get Request Method Call Object.

  1. The below source code snippet will use the OkHttp3 library to create an HTTP GET request.

3. Use OkHttp3 To Create HTTP Post Request Method Call Object.

  1. The below source code snippet will use the OkHttp3 library to create an HTTP POST request.

4. Send Http Request Synchronously And Asynchronously.

  1. You can send HTTP GET or POST requests with OkHttp3 synchronously or asynchronously.
  2. When you send the request synchronously, you need to run the code in a child thread because the process may take a long time.
  3. When you send the request asynchronously, the system will create a child thread and run OkHttp3 code in it automatically.

5. OkHttp Get Post Request Example.

Источник

Android HTTP Client: GET, POST, Download, Upload, Multipart Request

Often Android apps have to exchange information with a remote server using Android HTTP client. The easiest way is to use the HTTP protocol as a base to transfer information. There are several scenarios where the HTTP protocol is very useful like downloading an image from a remote server or uploading some binary data to the server. Android app performs GET or POST request to send data. In this post, we want to investigate how to use HttpURLConnection to communicate with a remote server.

As a server, we will use three simple Servlet running inside Tomcat 7.0. We won’t cover how to create a Servlet using API 3.0, you can find the source code here.

You can download the tutorial source code here:

GET and POST requests in Android HTTP Client

When developing Android HTTP client, GET and POST requests are the base blocks in HTTP protocol. To make this kind of requests we need first to open a connection toward the remote server:

[java] HttpURLConnection con = (HttpURLConnection) ( new URL(url)).openConnection();
con.setRequestMethod(«POST»);
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
[/java]

In the first line we get the HttpURLConnection, while in line 2, we set the method and at the end we connect to the server.
Once we have opened the connection we can write on it using the OutputStream.

As we already know parameters are written using key-value pair.
The last step is reading the response, using the InputStream:

[java]InputStream is = con.getInputStream();
byte[] b = new byte[1024];
while ( is.read(b) != -1)
buffer.append(new String(b));
con.disconnect();[/java]

Everything is very simple by now, but we have to remember one thing: when android HTTP client makes an HTTP connection, this operation is a time- consuming operation that could require a long time, sometime so we can’t run it on the main thread otherwise we could get a ANR problem. To solve it we can use an AsyncTask.

@Override
protected void onPostExecute(String result) <
edtResp.setText(result);
item.setActionView(null);
>
>[/java]

Running the app we get:

As we can see we post a name to the server and it responds with the classic ‘Hello….’. On the server side we can check that the server received correctly our post parameter:

Download data from server to Android app

One of the most common scenario when developing Android HTTP client is when an Android App has to download some data from a remote server. We can suppose that we want to download an image from the server. In this case we have always to use an AsyncTask to complete our operation, the code is shown below:

[java]public byte[] downloadImage(String imgName) <
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try <
System.out.println(«URL [«+url+»] – Name [«+imgName+»]»);

HttpURLConnection con = (HttpURLConnection) ( new URL(url)).openConnection();
con.setRequestMethod(«POST»);
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
con.getOutputStream().write( («name=» + imgName).getBytes());

InputStream is = con.getInputStream();
byte[] b = new byte[1024];

while ( is.read(b) != -1)
baos.write(b);

con.disconnect();
>
catch(Throwable t) <
t.printStackTrace();
>

Читайте также:  Android все папки пусты

return baos.toByteArray();
>[/java]

This method is called in this way:

[java] private class SendHttpRequestTask extends AsyncTask&amp;amp;amp;lt;String, Void, byte[]&amp;amp;amp;gt; <

@Override
protected byte[] doInBackground(String… params) <
String url = params[0];
String name = params[1];

HttpClient client = new HttpClient(url);
byte[] data = client.downloadImage(name);

@Override
protected void onPostExecute(byte[] result) <
Bitmap img = BitmapFactory.decodeByteArray(result, 0, result.length);
imgView.setImageBitmap(img);
item.setActionView(null);
>
>
[/java]

Running the app we have:

Upload data to the server using MultipartRequest

This the most complex part in developing Android HTTP client is handling HTTP connection. Natively HttpURLConnection doesn’t handle this type of request. It can happen that an Android App has to upload some binary data to the server. It can be that an app has to upload an image for example. In this case,the request gets more complex, because a “normal” request isn’t enough. We have to create a MultipartRequest.

A MultipartRequest is a request that is made by different parts as parameters and binary data. How can we handle this request?

Well the first step is opening a connection informing the server we want to send some binary info:

[java] public void connectForMultipart() throws Exception <
con = (HttpURLConnection) ( new URL(url)).openConnection();
con.setRequestMethod(«POST»);
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty(«Connection», «Keep-Alive»);
con.setRequestProperty(«Content-Type», «multipart/form-data; boundary=» + boundary);
con.connect();
os = con.getOutputStream();
>[/java]

In lines 6 and 7, we specify the request content-type and another field called boundary. This field is a char sequence used to separate different parts.

For each part, we want to add we need to specify if it is text part like post parameter or it is a file (so binary data).

[java] public void addFormPart(String paramName, String value) throws Exception <
writeParamData(paramName, value);
>

private void writeParamData(String paramName, String value) throws Exception <
os.write( (delimiter + boundary + «rn»).getBytes());
os.write( «Content-Type: text/plainrn».getBytes());
os.write( («Content-Disposition: form-data; name=»» + paramName + «»rn»).getBytes());;
os.write( («rn» + value + «rn»).getBytes());
>[/java]

[java]private String delimiter = «–»;
private String boundary = «SwA»+Long.toString(System.currentTimeMillis())+»SwA»;
[/java]

To add a file part we can use:

[java] public void addFilePart(String paramName, String fileName, byte[] data) throws Exception <
os.write( (delimiter + boundary + «rn»).getBytes());
os.write( («Content-Disposition: form-data; name=»» + paramName + «»; filename=»» + fileName + «»rn» ).getBytes());
os.write( («Content-Type: application/octet-streamrn» ).getBytes());
os.write( («Content-Transfer-Encoding: binaryrn» ).getBytes());
os.write(«rn».getBytes());

So in our app we have:

[java] private class SendHttpRequestTask extends AsyncTask&amp;amp;amp;lt;String, Void, String&amp;amp;amp;gt; <
@Override
protected String doInBackground(String… params) <
String url = params[0];
String param1 = params[1];
String param2 = params[2];
Bitmap b = BitmapFactory.decodeResource(UploadActivity.this.getResources(), R.drawable.logo);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.compress(CompressFormat.PNG, 0, baos);

try <
HttpClient client = new HttpClient(url);
client.connectForMultipart();
client.addFormPart(«param1», param1);
client.addFormPart(«param2», param2);
client.addFilePart(«file», «logo.png», baos.toByteArray());
client.finishMultipart();
String data = client.getResponse();
>
catch(Throwable t) <
t.printStackTrace();
>

@Override
protected void onPostExecute(String data) <
item.setActionView(null);
>

Running it we have:

At the end of this post, you know how to handle HTTP connections using Android and how to send and retrieve data using standard HTTP library shipped with Android.

Источник

How to Send JSON Data in a POST Request in Android

Retrofit2 is a powerful HTTP client library developed by Square used in Android and Java development. I have put together a tutorial with code samples in Java covering how to send JSON data in a HTTP POST request within an Android app using Retrofit2.

To send JSON data in a POST request in Android using Retrofit2 you need to complete the following steps.

  1. Obtain the dependencies for Retrofit2 using Gradle
  2. Create the model for the API request and response
  3. Create a Java interface representing the service and including Retrofit2 annotations
  4. Set up the HTTP client using a singleton pattern within your app
  5. Invoke the HTTP client generating the request and handling the response and errors
  6. Configure the app manifest to give permission to access the internet

Continue reading this post to deep dive into what Retrofit2 is and how it can be used to generate a POST request containing JSON data with code samples available in this article in Java.

I have also added some information to the tutorial around an alternative approach for sending data in a POST request with Retrofit2 by using URL parameters instead of a JSON body inside the request.

Android HTTP JSON Body Post Request in Java Using Retrofit2 Example

We will be creating a very basic Android app for this tutorial to demonstrate how to make a HTTP POST request containing a JSON body using Retrofit2.

Please see a screenshot of the Android app will be creating. The app contains a basic form that is used to capture a comment which is like something that you might see on a social media app or a news app with articles the public can comment on.

As you can see it contains the following:

  • Three fields for capturing a Comment including a title, a body and an author
  • A radio button group containing three different options for creating the HTTP POST request using Retrofit2
  • And a button to send the HTTP POST request containing the data about the Comment

I have uploaded the code for the Android app being created in this tutorial in GitHub – https://github.com/learntodroid/PostRequestwithJSON

For the purposes of this tutorial I have written code for a very basic API using Python and the library Flask which is configured to respond with the same Comment sent to the API in POST request from the Android app.

If you are interested in the code for the API written in Python using the Flask library it is also available on GitHub – https://github.com/learntodroid/PostRequestFlaskApi

If you want to run this API make sure you have Python and PyPi installed on your local machine where you are running the Android emulator and follow the brief instructions in the Readme to retrieve the dependencies for Flask and run the API.

Step 1: Obtaining the Retrofit2 Dependencies

In this tutorial we will be making use of various 3rd party libraries to simplify the effort required to integrate our Android app with an API to make a POST request.

The 3rd party libraries we will use include Retrofit2, OkHttp3 and GSON. Each of the libraries will be retrieved into our Android project using Gradle.

Читайте также:  69 days after android rus

Retrofit2

Retrofit2 is a HTTP client for Android and Java developed by Square which allows you to use a Java interface to simplify the process of integrating with a HTTP API.

To retrieve the Retrofit2 library using Gradle include the following implementation dependency inside your app’s build.gradle file (see a complete build.gradle file at the end of this section which covers all required dependencies).

Retrofit2 requires Java 8, to include Java 8 in an Android project, update your app’s build.gradle file to include compile options.

OkHttp3

OkHttp3 is a HTTP client for Java and Kotlin developed by Square.

For the purposes of this tutorial we will be using the logging interceptor included in the OkHttp3 library to give us visibility of the HTTP request and response logs for our Android app within Logcat.

To get an idea of what we will be able to see in Logcat using the OkHttp3 logging interceptor, have a look at the screenshot below

To retrieve the logging interceptor from the OkHttp3 library using Gradle include the following implementation dependency inside your app’s build.gradle file.

Gson is a Java library by Google that supports converting objects in Java into JSON format and back otherwise known as serialization and deserialization.

Retrofit2 has added support for different converters including GSON to support serialization and deserialization when handling an API’s request and response.

To retrieve the GSON converter from the Retrofit2 library using Gradle include the following implementation dependency inside your app’s build.gradle file.

The list of converters supported by Retrofit2 are:

Example ‘build.gradle’ Containing Retrofit2, OkHttp3 & GSON Dependencies

Please see the example build.gradle file covering all the dependencies highlighted in the section above.

Step 2: Creating the Model for the API Request and Response

The comments we will capture in our Android app with contain three attributes entered by the user. These three attributes will all be strings and will contain the comment author, a title for the comment and a body for the comment.

When we will be make a POST request to the API, we will use the GSON library to transform a Comment object into a JSON string (serialization) to send inside the body of the request.

If the request was correctly formatted the API will request with the same JSON file we can then use GSON to transform that JSON string and transform it into a Comment object (deserialization).

When building the model class, use the @SerializedName(string) annotation against each field to set the name of the attribute as it will appear in the JSON file. By default GSON will use the variable name in Java if there is no @SerializedName(string) annotation provided.

Please see the example class below containing the model for a comment.

Step 3: Creating a Java Interface for the API with Retrofit2

In this section of the tutorial we will be creating a Java interface and use the Retrofit2 library to add annotations to methods in the interface that will represent the operations exposed on the API.

Please see the example Java interface using Retrofit2 annotations to describe the API will we be using to submit Comments.

In this section we will focus the createComment(Comment) method defined on line 14.

Line 13, contains both the request method and path that will be called on the API when the createComment(Comment) method is invoked. In this case we are using a POST request so we use the “@POST” Retrofit2 annotation. We will be sending the POST request to the “/comments” end point on the API so inside we pass the path as a parameter to the “@POST” annotation.

The full list of request methods supported by Retrofit2 are:

On line 14, we are defining the method for creating a comment and we are passing a @Body annotation with a Comment object as a parameter. Providing an @Body annotation with a Comment as a parameter indicates that we will be providing a request body when we invoke this API which in our case will be a JSON payload containing the details of the comment.

The finally, the createComment(Comment) method returns a Call object. This means that when we invoke the API to create the comment we expect to see a request body containing a JSON body that we will deserialize into a Comment object (in our case using Gson).

Step 4: Setting Up the HTTP Client

In this part of the tutorial we will setting up access to the HTTP client using Retrofit2 inside a repository class that follows the singleton pattern. This will enable us in the next step of tutorial to retrieve the instance of the repository then invoke the API to create a comment.

Please see the code below containing the CommentsRepository class which initialises the HTTP client using Retrofit2 inside the constructor.

Inside the constructor prior to setting up the API using Retrofit2 first we create an interceptor using the OkHttp3 library that we will use to allow us to log the HTTP request and responses inside Logcat. We create also use the OkHttp3 library for it’s HTTP client when interacting with the API.

Using the Retrofit2 API builder we provide it with the base url of the API, we set the client to the OkHttp3 client and specify we will be using the Gson library for converting API request and response payloads.

With regards to the base url, I have set it to use the host of “http://10.0.2.2” and the port number 5000. This is because I will use flask to run on it’s default port which is port 5000, and run it on the same host as where I am running the Android emulator.

You cannot use “localhost” as the host for the Android emulator because as I learned in this helpful Stackoverflow answer localhost on the Android emulator will point to the emulator’s own loopback service and you need to use “10.0.2.2” instead to access your local machine.

Читайте также:  Все для андроида huawei

And finally we create a reference to the web service using the interface of the API we defined in step 3.

Step 5: Invoking the API using Retrofit2

In this section of the tutorial for sending a JSON payload inside a POST request using Retrofit2 we will be creating our Activity that will invoke the API using Retrofit2.

Please see the code below containing the CommentsActivity class which invokes the HTTP client with a POST request using Retrofit2 when the button is clicked.

Inside the onCreate(Bundle) method we will get access to the single instance of the CommentsRepository which we will use in the OnClickListener assigned to the Button to generate a HTTP request to the Comments API.

Inside the OnClickListener we first create the Comment object using the comment title, comment author and comment body captured by the use.

Then using a switch statement check for which radio button was selected, in this section I will only cover the option sending the JSON payload which is defined in lines 55 – 66.

To invoke the API we access the CommentService on the CommentRepository and call the createComment(Comment) method passing the Comment object we created based on the user input.

We call the createComment(Comment) method using enqueue which allows use to define a callback method in case of either a response (defined in an onResponse method) or failure (defined in a onFailure method).

In the onResponse method we expect to see a Comment object in the response and we use a toast to show the comment text which is present inside the HTTP response JSON body that gets deserialized into a Comment object using Gson.

In the onFailure method we simply display the error encountered using a toast, this may occur if the API is down, if there are connectivity issues, or there is a coding error on the server side API.

I have also included the layout resource below which I used for the CommentActivity class.

Step 6: Configure the Manifest to Access the Internet

One final thing you will need to do to ensure you have connectivity to the API is to enable the permission to access the internet (android.permission.INTERNET) inside your Android Manifest for your app.

In addition to this, if you are going to use the Flask API I wrote and don’t want to configure a HTTPS certificate for the API, you will need to add an attribute in the application tag (by setting “android:usesCleartextTraffic” to “true”) inside the Android Manifest to specify that you want to send clear text traffic in your Android app. Warning: Sending clear text traffic should not be done in production for security reasons.

See the sample AndroidManifest.xml file below the shows how to configure the use of clear text traffic and setting the permission to access the internet.

Demonstration

Now if you run your Android app with the API running, and include the comment details and click the button, you should see something like the following in Logcat.

Sending Data in URL Parameters using a POST Request with Retrofit2

Retrofit2 also has support for sending data in a POST request using parameters within the URL.

To achieve this using Retrofit2 inside the interface class you need to add @FormUrlEncoded annotation above the method name. For an example of this check out lines 16 and 20 in the interface code shared in Step 3 of this tutorial you will see the use of the @FormUrlEncoded annotation.

To see the difference in the logs when using the @FormUrlEncoded annotation compare the Logcat results from the Demo section above to the results using the @FormUrlEncoded annotation below.

As you can see one difference is that the Content-Type in the header of the request is to set “application/x-www-form-urlencoded”. Another difference is that instead of a request body the the title, comment and author appear in an encoded format in the URL.

How to Use @Field and @FieldMap in Retrofit2

When making a request to an API defined in Retrofit2 you opt to pass the attributes to be sent in the request as a set of fields or as a set of key value pairs.

Using @Field Annotation in Retrofit2

If you check out line 18 in the interface code shared in Step 3 of this tutorial you will see the use of the @Field annotation. Each of the field names and their data types are defined in the method parameters inside the interface.

If you have a look at line 69 in the activity code shared in Step 5 of this tutorial you will see that instead of passing the Comment object as a parameter to the createComment method, the title, comment and author are passed as individual strings instead.

Using @FieldSet Annotation in Retrofit2

If you check out line 22 in the interface code shared in Step 3 of this tutorial you will see the use of the @FieldMap annotation. A Map contain keys that are Strings and values that are Strings are defined as a parameter for that method inside the interface.

If you have a look at lines 83 to 87 in the activity code shared in Step 5 of this tutorial you will see that instead of passing the Comment object as a parameter to the createComment method, a HashMap is passed as an parameter. This HashMap contains key value pairs of which the field names are defined as the keys and the comment title, comment body and comment author are defined as the values.

Further Reading

If you want to learn using the Model View ViewModel software design pattern with Retrofit2 to integrate your Android app with an API, check out the other post I wrote below that goes into this.

Источник

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