- Post to server android
- Android OkHttp Example
- OkHttp Supports Http/2
- Features of OkHttp.
- Add Library to Project
- Add Permission to Manifest
- Android OkHttp Examples
- Android OkHttp Get Example
- Android OkHttp Get Request With Query String Example
- Android OkHttp Post Example
- Android OkHttp POST JSON Example
- Android OkHttp Headers Example
- Android OkHttp Async Call
- Android OkHttp Multipart Example
- Android OkHttp Example Code
- Activity
- Layout
- About
- Android OkHttp3 Http Get Post Request Example
- 1. OKHttp Characters.
- 2. Add OkHttp3 Library In build.gradle.
- 2. Use OkHttp3 To Create HTTP Get Request Method Call Object.
- 3. Use OkHttp3 To Create HTTP Post Request Method Call Object.
- 4. Send Http Request Synchronously And Asynchronously.
- 5. OkHttp Get Post Request Example.
- How to Send Data From Android to PHP Server? Android Post Request Help
- Download HttpComponents Library
- How To Post Text Data?
- How To Post A File?
- Complete Android Code on How to Send Data From Android to PHP Server
- PHP file that will receive the posted data
- AndroidManifest.xml Code
- Output Screenshots
Post to server android
Android OkHttp Example
May 27, 2017 by Srinivas
Android apps rely on rest services running on server for authentication & authorization, getting and posting data. Since the services on the web run on http protocol, in order to network with servers, android apps need http client. While there are several http client libraries and frameworks including volley which can be used in Android, OkHttp, an Http & Http/2 client, is widely used in android and java applications.
In this article, I am going to explain features of OkHttp and show how to use OkHttp in android to make http get, post, multipart, json and asynchronous request calls with examples.
OkHttp Supports Http/2
Below are some of the features of http/2
- Http/2 is a binary protocol which is more efficient compared to text protocol Http.
- Http/2 supports multiplexing meaning multiple requests and responses can be in flight at the same time on a connection.
- Http/2 supports header compression leading to reduced network round trips.
- Http/2 provides improved security.
Features of OkHttp.
OkHttp supports below features which make OkHttp an efficient http client with fast loading and reduced network bandwidth.
- OkHttp supports Http/2 protocol.
- Connection pooling can used for http protocol connections.
- GZIP compression shrinks network data size.
- Cache eliminates network round trip for repeating requests.
- OkHttp silently recovers from network problems.
- If your server is load balanced, OkHttp tries to connect other nodes when it fails to connect one of the nodes in load balancer.
- OkHttp supports both synchronous and asynchronous calls.
- You can use OkHttp on Android 2.3 and Java 7 versions onwards.
Add Library to Project
You can add OkHttp library to your project by adding below line to your module gradle property file.
Add Permission to Manifest
As below examples access rest services on server, internet permission is required. Add below permission to manifest xml file.
Android OkHttp Examples
In the below examples, the process of making reset service calls and updating UI with responses is executed in the background thread using AsyncTask. I provided below detailed explanation of each type of http request and complete android OkHttp example code.
Android OkHttp Get Example
Below code shows how to send http get request using OkHttp. To make an http get request call using OkHttp, you need to create Request object by using Request.Builder. Then call newCall method on OkHttpClient object passing the Request object. Finally, call execute() method on Call object to make http get request and receive response.
Above service call returns response in JSON format. Once you get JSON string from response by calling response.body().string(), you can use JSONOjbect or gson for parsing it. If you need more information on how to parse json in android, you can view my previous posts parsing JSON using JSONObject and parsing Json using gson library.
Android OkHttp Get Request With Query String Example
To make http get request call with query parameter using OkHttp, you need to use HttpUrl.Builder and add query parameter to it by calling addQueryParameter on HttpUrl.Builder as shown in below code.
Android OkHttp Post Example
To add post data to Request as key value pairs like data from html forms, you need to use FormBody.Builder, add post parameters to it, and create RequestBody as shown below.
Android OkHttp POST JSON Example
You can post json string to server using OkHttp. To do that, you need to create RequestBody object using create method on RequestBody passing json MediaType and json string as show below.
Android OkHttp Headers Example
You can add headers to request when request object is created or in intercepters by calling addHeader method on Request.Builder object.
Android OkHttp Async Call
In our examples, as UI needs to be updated with response after service call, entire process of making service calls and updating UI is done in the background using AsyncTask. But if you don’t need to use AsyncTask but only want to make http call asynchronously, you can do so by calling enqueue method on Call object passing Callback instead of execute method which makes http call synchronously.
Android OkHttp Multipart Example
To upload files or send multiple parts to http server, you need to send http multipart request. You can create multipart requests in OkHttp by building RequestBody using MultipartBody.Builder shown below. MultipartBody.Builder allows you to add data parts using addFormDataPart method.
Android OkHttp Example Code
Activity
Layout
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник
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.
- OkHttp3 is a third-party open-source library that is contributed by the square company. It has below characters.
- User-friendly API.
- Support http2, sharing the same socket for all requests from a machine.
- Built-in connection pool, support for connection reuse, and reduction of delay.
- Supports transparent gzip compression response.
- Avoid duplicate requests by caching.
- Automatically retry the host’s other IP and redirect automatically when the request fails.
2. Add OkHttp3 Library In build.gradle.
- Before you can use the OkHttp3 library, you need to add dependencies in the build.gradle file in android studio as below.
- You can get the most recent build library from https://github.com/square/okhttp.
- 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.
- 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.
- The below source code snippet will use the OkHttp3 library to create an HTTP POST request.
4. Send Http Request Synchronously And Asynchronously.
- You can send HTTP GET or POST requests with OkHttp3 synchronously or asynchronously.
- When you send the request synchronously, you need to run the code in a child thread because the process may take a long time.
- 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.
Источник
How to Send Data From Android to PHP Server? Android Post Request Help
Hi guys! Today we are going to code on how to send data from Android to PHP server. This is an example app that can post a file and text data to a web server with PHP file as a receiver. Having the ability to (do HTTP Post Request) post data from android app to remote server is required for most apps. Here are some example use of this functionality:
1. You want to get statistics on how your app is being used (you have to tell your user and they must agree of course!)
2. Your app has an upload file feature.
3. A user should register on your database before using more features of your app.
Download HttpComponents Library
In this example, we are using a small library for posting a file, it is called the HttpComponents from the Apache Software Foundation. Please note that you won’t need this library if you’re just posting text data. The download can be found here: HttpComponents
- As of the moment, I downloaded the binary 4.2.3.zip
- When you extracted the zip file, find the lib folder and copy all the jar files there
- Copy those jar files to your project’s lib folder, here’s how to do that:
- Go to your workspace directory, find your project folder and inside, find the libs folder, put the jar files we extracted earlier
- Go back to eclipse and refresh your project files in the project explorer, now you can see the jar files inside your lib directory. See the screenshot below to visualize the goal of these 5 steps above.
How To Post Text Data?
How To Post A File?
You can use this code to post other file types such as an image.
Complete Android Code on How to Send Data From Android to PHP Server
This is our MainActivity.java code. In this code, we are:
- Using AsyncTask to prevent the network on main thread error.
- To test posting the text data, you must change the actionChoice variable value to 1.
- Else if you are to test posting a sample file, you must change the actionChoice to 2. Also, don’t forget to put a sample.txt file in your SD card root directory.
The code above should give you a lot of clue on how to send data from Android to PHP server. But we have few more steps to do, continue to read below.
PHP file that will receive the posted data
This is the post_date_receiver.php code. You must upload it in your server and specify the URL to our MainActivity.java
AndroidManifest.xml Code
Well, we are just having an INTERNET permission here.
Output Screenshots
Response is what post_date_receiver.php outputs when it receives the posted data.
Posting Text Data. The response array have our key-value pairs.
Posting Text File. The response is the content of my sample.txt file.
What do you think fo this code I came up with? If you have a better solution about how to send data from Android to PHP server, please let us know in the comments section below! We will add your solution or update this post if it deserves to, thanks!
Share this entry
Do you have any suggestion when we want to send BOTH string and file in one go? Suppose we want to create a feature which user can post a picture with some captions. How do we proceed with that?
Hey @Curious, how about putting those two methods in a single method and execute one after the other?
I’m trying to post data to a website from Android. The website just shows empty. How does the website refresh when it gets data? is the command $_POST always looking for data or does it only see the second it is sent?
The php server i’m trying to upload my file to requires authentication. How can i send the username and password before attempting the upload?
Hi @Rohan D, thanks for your query, I’ll have to make a new post for this one!
Dear Sir,
I need help in sending data to server with android code.I have an api example
http://getepass.com/api.php?action=login&&email=aaa@gmail.com&&password=root
I want to send email and password to server from mobile text and receive few parameter image ,name,compid etc and then show in app.
I am using a lib for this but I want to code it myself If possible please send me the example to post and read the json from server in android.
Thanks!
Prachi Gupta
Hey you could use it, its complete code here
android code start here
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.EventLogTags.Description;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint(“NewApi”)
public class xxx extends Activity< //implements OnClickListener
@SuppressLint(“NewApi”)
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
@Override
protected void onCreate(Bundle savedInstanceState) <
super.onCreate(savedInstanceState);
setContentView(R.layout.xxx);
post =(Button)findViewById(R.id.postButton);
post.setOnClickListener(new OnClickListener() <
@Override
public void onClick(View v) <
// TODO Auto-generated method stub
String result = null;
InputStream is = null;
EditText editText=(EditText)findViewById(R.id.name_forkeyfound);
String name=editText.getText().toString();
EditText editText6=(EditText)findViewById(R.id.contect_keyfound);
String contact_no=editText6.getText().toString();
EditText editText3=(EditText)findViewById(R.id.Email_forkeyfound);
String email=editText3.getText().toString();
EditText editText8=(EditText)findViewById(R.id.membership_keyfound);
String membership=editText8.getText().toString();
EditText editText9=(EditText)findViewById(R.id.description_keyfound);
String we_found=editText9.getText().toString();
ArrayList nameValuePairs = new ArrayList();
Log.d(“well2”, “msg”);
StrictMode.setThreadPolicy(policy);
Log.d(“well3”, “msg”);
//http post
try <
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(“http://10.0.2.2/my_folder_inside_htdocs/xxx.php”);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d(“well4”, “msg”);
Log.e(“log_tag”, “connection success “);
Toast.makeText(getApplicationContext(), “Please Wait….”, Toast.LENGTH_SHORT).show();
>
catch(Exception e)
<
Log.e(“log_tag”, “Error in http connection “+e.toString());
Toast.makeText(getApplicationContext(), “Connection fail”, Toast.LENGTH_SHORT).show();
Log.d(“well5”, “msg”);
>
//convert response to string
Log.d(“well5”, “msg”);
try <
BufferedReader reader = new BufferedReader(new InputStreamReader(is,”iso-8859-1″),8);
StringBuilder sb = new StringBuilder();
Log.d(“well6”, “msg”);
String line = null;
while ((line = reader.readLine()) != null)
<
sb.append(line + “n”);
Intent i = new Intent(getBaseContext(),keyfound.class);
startActivity(i);
>
is.close();
result=sb.toString();
>
catch(Exception e)
<
Log.e(“log_tag”, “Error converting result “+e.toString());
Log.d(“well7”, “msg”);
>
JSONObject json_data = new JSONObject(result);
Источник