OKhttp基本使用介绍

MainActivity.class

  1 package com.example.administrator.okhttp3;
  2 
  3 import android.support.v7.app.AppCompatActivity;
  4 import android.os.Bundle;
  5 import android.util.Log;
  6 import android.view.View;
  7 import android.widget.Button;
  8 import android.widget.TextView;
  9 
 10 import java.io.File;
 11 import java.io.FileOutputStream;
 12 import java.io.IOException;
 13 import java.io.InputStream;
 14 
 15 import okhttp3.Call;
 16 import okhttp3.Callback;
 17 import okhttp3.FormBody;
 18 import okhttp3.OkHttpClient;
 19 import okhttp3.Request;
 20 import okhttp3.RequestBody;
 21 import okhttp3.Response;
 22 
 23 public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 24     private static OkHttpClient client = new OkHttpClient();
 25     private Request request;
 26     private Response response;
 27 
 28     private Button button1, button2, button3, button4;
 29     private TextView textView;
 30 
 31     @Override
 32     protected void onCreate(Bundle savedInstanceState) {
 33         super.onCreate(savedInstanceState);
 34         setContentView(R.layout.activity_main);
 35         button1 = (Button) findViewById(R.id.btn_one);
 36         button2 = (Button) findViewById(R.id.btn_two);
 37         button3 = (Button) findViewById(R.id.btn_three);
 38         button4 = (Button) findViewById(R.id.btn_four);
 39         button1.setOnClickListener(this);
 40         button2.setOnClickListener(this);
 41         button3.setOnClickListener(this);
 42         button4.setOnClickListener(this);
 43         textView = (TextView) findViewById(R.id.tv);
 44     }
 45 
 46     @Override
 47     public void onClick(View view) {
 48         switch (view.getId()) {
 49             case R.id.btn_one://同步get
 50                 client = new OkHttpClient();
 51                 request = new Request.Builder().url("http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9").build();
 52                 new Thread(new Runnable() {
 53                     @Override
 54                     public void run() {
 55                         try {
 56                             response = client.newCall(request).execute();
 57                             final String src = response.body().string();
 58                             Log.e("Tag", response.body().string());
 59                             runOnUiThread(new Runnable() {
 60                                 @Override
 61                                 public void run() {
 62                                     textView.setText(src);
 63                                 }
 64                             });
 65 
 66                         } catch (IOException e) {
 67                             e.printStackTrace();
 68                         }
 69                     }
 70                 }).start();
 71 
 72                 break;
 73             case R.id.btn_two://异步get
 74                 request = new Request.Builder().url("http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9").build();
 75                 client.newCall(request).enqueue(new Callback() {
 76                     @Override
 77                     public void onFailure(Call call, IOException e) {
 78 
 79                     }
 80 
 81                     @Override
 82                     public void onResponse(Call call, Response response) throws IOException {
 83                         final String src = response.body().string();
 84                         Log.e("Tag", response.body().string());
 85                         runOnUiThread(new Runnable() {
 86                             @Override
 87                             public void run() {
 88                                 textView.setText(src);
 89                             }
 90                         });
 91                     }
 92                 });
 93                 break;
 94             case R.id.btn_three://提交表单
 95                 RequestBody requestBody = new FormBody.Builder()
 96                         .add("search", "papap").build();
 97                 request = new Request.Builder().url("https://en.wikipedia.org/w/index.php").post(requestBody).build();
 98                 client.newCall(request).enqueue(new Callback() {
 99                     @Override
100                     public void onFailure(Call call, IOException e) {
101 
102                     }
103 
104                     @Override
105                     public void onResponse(Call call, Response response) throws IOException {
106                         final String src = response.body().string();
107                         runOnUiThread(new Runnable() {
108                             @Override
109                             public void run() {
110                                 textView.setText(src);
111                             }
112                         });
113                     }
114                 });
115                 break;
116             case R.id.btn_four://文件下载
117                 request = new Request.Builder().url("http://pic2.ooopic.com/10/18/01/04bOOOPICb3.jpg").build();
118                 client.newCall(request).enqueue(new Callback() {
119                     @Override
120                     public void onFailure(Call call, IOException e) {
121 
122                     }
123 
124                     @Override
125                     public void onResponse(Call call, Response response) throws IOException {
126                         InputStream inputStream = response.body().byteStream();
127                         FileOutputStream fileOutputStream = new FileOutputStream(new File("/sdcard/tupian.jpg"));
128                         byte[] buffer = new byte[2048];//每次循环读取2K的数据
129 
130                         int len = 0;
131                         while ((len = inputStream.read(buffer)) != -1) {
132                             fileOutputStream.write(buffer, 0, len);
133                         }
134                         fileOutputStream.flush();
135 
136                         runOnUiThread(new Runnable() {
137                             @Override
138                             public void run() {
139                                 textView.setText("文件下载成功。。。");
140                             }
141                         });
142                     }
143                 });
144                 break;
145         }
146     }
147 }


PS:需要注意的是,在进行同步Get网络请求时,因为都是一个耗时操作,所以需要建立一个子线程去进行请求; 并且,UI界面的更新,必须放在主线程去完成!

activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:orientation="vertical"
 7     android:paddingBottom="@dimen/activity_vertical_margin"
 8     android:paddingLeft="@dimen/activity_horizontal_margin"
 9     android:paddingRight="@dimen/activity_horizontal_margin"
10     android:paddingTop="@dimen/activity_vertical_margin"
11     tools:context="com.example.administrator.okhttp3.MainActivity">
12 
13     <Button
14         android:id="@+id/btn_one"
15         android:layout_width="wrap_content"
16         android:layout_height="wrap_content"
17         android:text="同步get" />
18 
19     <Button
20         android:id="@+id/btn_two"
21         android:layout_width="wrap_content"
22         android:layout_height="wrap_content"
23         android:text="异步get" />
24 
25     <Button
26         android:id="@+id/btn_three"
27         android:layout_width="wrap_content"
28         android:layout_height="wrap_content"
29         android:text="Post提交表单" />
30 
31     <Button
32         android:id="@+id/btn_four"
33         android:layout_width="wrap_content"
34         android:layout_height="wrap_content"
35         android:text="文件下载" />
36 
37     <TextView
38         android:id="@+id/tv"
39         android:layout_width="wrap_content"
40         android:layout_height="wrap_content"
41         android:text="text"/>
42 </LinearLayout>

原文地址:https://www.cnblogs.com/huolongluo/p/5915417.html