A brief introduction and use of Okhttp

### Preface: Through this article, we can know some points:

  • Network request evolution in Android
  • What is okhttp
  • Simple use of okHTTP

If you’re interested, check out my other post, a simple encapsulation of OKHTTP:

  • http://blog.csdn.net/wuyinlei/article/details/50598783

Network request development:

  • HttpURLConnection—>Apache HTTP Client—>Volley—->okHttp

What OkHttp is:

  • Project open source address: https://github.com/square/okhttp
  • Project use: Add dependencies to build.gradleThe compile 'com. Squareup. Okhttp3: okhttp: 3.0.1'

OkHttp is an efficient HTTP library:

  • 1. SPDY is supported, sharing the same Socket to process all requests from the same server
  • 2. If SPDY is unavailable, use connection pooling to reduce request latency
  • 3. Seamless GZIP support to reduce data traffic
  • 4. Cache response data to reduce repeated network requests

Advantages:

  • OkHttp automatically recovers from many common connection problems. If your server is configured with multiple IP addresses, if the first IP address fails to connect, the next IP address will be automatically tried. OkHttp also handles proxy server issues and SSL handshake failures.
  • Using OkHttp does not require rewriting the network code in your program. OkHttp realized almost as well as the java.net.HttpURLConnection API. If you use Apache HttpClient, OkHttp also provides a corresponding okHTTP-Apache module

The basic use of ####Okhttp is explained from the following five aspects:

  • 1.Get requests (synchronous and asynchronous)
  • 2.POST request form (key-value)
  • 3.POST request submission (JSON/String/ file etc.)
  • 4. Download files
  • 5. Set the request timeout

####GET Request synchronization method

       OkHttpClient client=new OkHttpClient();
       Request request = new Request.Builder().url(url) .build();
       Response response= client.newCall(request).execute();
       String message=response.body().string();
Copy the code

####GET Request asynchronous method

        OkHttpClient client=new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                    }
                    @Override
                    public void onResponse(Response response) throws IOException {
                    }
         });

Copy the code

####POST request submission to explain here, when I was using 3.0, I went to look for FormEncodingBuilder(), but could not find this method, so I went to its official website to check the information, and found the following explanation:

  • We’ve replaced the opaque FormEncodingBuilder with the more powerful FormBody and FormBody.Builder combo. Similarly we’ve upgraded MultipartBuilder into MultipartBody, MultipartBody.Part, and MultipartBody.Builder.

Okhttp3.0 before:

      OkHttpClient client = new OkHttpClient();
	  RequestBody forBody = new FormEncodingBuilder().add("username"."tom").add("password"."1110").build();
                Request request=new Request.Builder().url(url).post(forBody).build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                    }
                    @Override
                    public void onResponse(Response response) throws IOException {
                        Log.d("xiaoming",response.body().string()); }});Copy the code

After okhttp3.0

   OkHttpClient client = new OkHttpClient();
   FormBody formBody = new FormBody.Builder()
                .add("type"."1")
                .build();
  Request request=new Request.Builder().url(url).post(forBody).build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                    }
                    @Override
                    public void onResponse(Response response) throws IOException {
                        Log.d("xiaoming",response.body().string()); }});Copy the code

#### File Download

 String url = "http://www.0551fangchan.com/images/keupload/20120917171535_49309.jpg"; Request request = new request.builder ().url(url).build(); OkHttpClient client = new OkHttpClient(); client.newCall(request).enqueue(newCallback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream inputStream = response.body().byteStream();
                FileOutputStream fileOutputStream = new FileOutputStream(new File("/sdcard/logo.jpg"));
                byte[] buffer = new byte[2048];
                int len = 0;
                while((len = inputStream.read(buffer)) ! = -1) { fileOutputStream.write(buffer, 0, len); } fileOutputStream.flush(); Log.d("wuyinlei"."File downloaded successfully..."); }});Copy the code

#### Timeout setting:

Okhttp3.0 before:

	client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setWriteTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
Copy the code

After okhttp3.0:

		client.newBuilder().connectTimeout(10, TimeUnit.SECONDS);
        client.newBuilder().readTimeout(10,TimeUnit.SECONDS);
        client.newBuilder().writeTimeout(10,TimeUnit.SECONDS);
Copy the code

Here’s a demo of the result:

** Note: ** I don’t know why, I also added the permission to write sdcard, but it reminded me that I did not have the permission when downloading, I can only use the real machine, here through the log feedback download success:

Now let’s look at the code, the layout is very simple, four buttons, one TextView, I won’t explain it here

package com.example.okhttpdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button syncGet; private Button asyncget; private Button post; private Button fileDownload,fengzhuang; private TextView tvtext; private String result; Private OkHttpClient client; /** * set connection timeout directly here, initialize OkHttpClient */ private voidinit() {
        client = new OkHttpClient();
        client.newBuilder().connectTimeout(10, TimeUnit.SECONDS);
        client.newBuilder().readTimeout(10, TimeUnit.SECONDS);
        client.newBuilder().writeTimeout(10, TimeUnit.SECONDS);
    }

    private Request request;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); init(); initialize(); initListener(); } /** * event listener */ private voidinitListener() { syncGet.setOnClickListener(this); asyncget.setOnClickListener(this); post.setOnClickListener(this); fileDownload.setOnClickListener(this); fengzhuang.setOnClickListener(this); } /** * initialize the layout control */ private voidinitialize() {

        syncGet = (Button) findViewById(R.id.syncGet);
        asyncget = (Button) findViewById(R.id.asyncget);
        post = (Button) findViewById(R.id.post);
        tvtext = (TextView) findViewById(R.id.tv_text);
        fileDownload = (Button) findViewById(R.id.fileDownload);
        fengzhuang = (Button) findViewById(R.id.fengzhuang);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.syncGet:
                initSyncData();
                break;
            case R.id.asyncget:
                initAsyncGet();
                break;
            case R.id.post:
                initPost();
                break;
            case R.id.fileDownload:
                downLoadFile();
                break;
            case R.id.fengzhuang:
                break; } /** * get request synchronization method */ private voidinitSyncData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    request = new Request.Builder().url(Contants.SYNC_URL).build();
                    Response response = client.newCall(request).execute();
                    result = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvtext.setText(result);
                            Log.d("MainActivity"."hello"); }}); } catch (Exception e) { e.printStackTrace(); } } }).start(); } /** * asynchronous request */ private voidinitAsyncGet() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                request = new Request.Builder().url(Contants.ASYNC_URL).build();
                client.newCall(request).enqueue(new Callback() {

                    /**
                     * A call is a request that has been prepared forexecution. A call can be canceled. As this object * represents a single request/response pair (stream), It cannot be executed twice. * * * @param Call is an interface that is used to prepare and execute a request. @override public void onFailure(Call Call, IOException e) {log.d ("MainActivity"."Request failed"); } /** ** @param call @param Response is a response request * @throws IOException */ @override public void onResponse(call call, Throws IOException {/** * Then body().string() gets the requested data * it's better to use string() instead of toString () * toString () every class has, */ result = response.body().string(); runOnUiThread(newRunnable() {
                            @Override
                            public void run() { tvtext.setText(result); }}); }}); } }).start(); } /** * form submission */ private voidinitPost() {

        String url = "http://112.124.22.238:8081/course_api/banner/query";

        
        FormBody formBody = new FormBody.Builder()
                .add("type"."1")
                .build();
        request = new Request.Builder().url(url)
                .post(formBody).build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvtext.setText("Submission successful"); }}); }}); } }).start(); } /** * file download address */ private voiddownLoadFile() {
        String url = "http://www.0551fangchan.com/images/keupload/20120917171535_49309.jpg";
        request = new Request.Builder().url(url).build();
        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Throws IOException {InputStream InputStream = response.body().bytestream (); * <uses-permission android:name= * <uses-permission android:name="android.permission.INTERNET"/>
                 * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"FileOutputStream = new FileOutputStream(new File)"/sdcard/logo.jpg")); Byte [] buffer = new byte[2048]; int len = 0;while((len = inputStream.read(buffer)) ! Fileoutputstream. write(buffer, 0, len); } // Close the output stream fileOutputStream.flush(); Log.d("wuyinlei"."File downloaded successfully..."); }}); }}Copy the code

Ok, that’s it for the simple okHTTP usage, and the following simple encapsulation will be done.

Since OKHttp3.0 is a bit different than before, you can check out their official instructions when using it, so there will be less unnecessary trouble in using it.