当前位置:   article > 正文

Android:Okhttp3详解(get和post同步异步文件上传)

Android:Okhttp3详解(get和post同步异步文件上传)

准备工作

导入依赖

dependencies {
    implementation("com.squareup.okhttp3:okhttp:4.9.0")
}
  • 1
  • 2
  • 3

配置网络权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.networklearn1">

    <uses-permission android:name="android.permission.INTERNET"/>

</manifest>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

准备4个请求按钮

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get同步请求"
        android:onClick="get1"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="get异步请求"
        android:onClick="get2"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="post同步请求"
        android:onClick="post1"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="post异步请求"
        android:onClick="post2"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="post上传文件"
        android:onClick="uploadFile"/>

</LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

主页面配置okhttpClient对象

public class MainActivity extends AppCompatActivity {

    private OkHttpClient okHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        okHttpClient = new OkHttpClient();
    }

    public void get1(View view) {
    }

    public void get2(View view) {
    }

    public void post1(View view) {
    }

    public void post2(View view) {
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

Get同步请求

请求代码

public void get1(View view) {
        new Thread(){
            @Override
            public void run() {
                Request request = new Request.Builder()
                        .url("https://www.httpbin.org/get?a=1&b=2")
                        .build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    Log.i("test",response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

响应内容

I/test: {
      "args": {
        "a": "1", 
        "b": "2"
      }, 
      "headers": {
        "Accept-Encoding": "gzip", 
        "Host": "www.httpbin.org", 
        "User-Agent": "okhttp/4.9.0", 
        "X-Amzn-Trace-Id": "Root=1-6230a3bc-3cff97ac41773a7531d5fc08"
      }, 
      "origin": "117.143.100.243", 
      "url": "https://www.httpbin.org/get?a=1&b=2"
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Get异步请求

请求代码

public void get2(View view) {
        Request request = new Request.Builder()
                .url("https://www.httpbin.org/get?a=1&b=2")
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()){
                    Log.i("test",response.body().string());
                }
            }
        });
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

响应内容

I/e.networklearn: Waiting for a blocking GC ProfileSaver
I/e.networklearn: WaitForGcToComplete blocked ProfileSaver on HeapTrim for 33.822ms
I/test: {
      "args": {
        "a": "1", 
        "b": "2"
      }, 
      "headers": {
        "Accept-Encoding": "gzip", 
        "Host": "www.httpbin.org", 
        "User-Agent": "okhttp/4.9.0", 
        "X-Amzn-Trace-Id": "Root=1-6230a57f-7e16a25538f5ec0a55c224b2"
      }, 
      "origin": "117.143.100.243", 
      "url": "https://www.httpbin.org/get?a=1&b=2"
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

Post同步请求

请求代码

public void post1(View view) {

        new Thread(){
            @Override
            public void run() {
                FormBody formBody = new FormBody.Builder()
                        .add("a","1")
                        .add("b","1")
                        .build();
                Request request = new Request.Builder()
                        .url("https://www.httpbin.org/post")
                        .post(formBody)
                        .build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    Log.i("test",response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

响应内容

I/test: {
      "args": {}, 
      "data": "", 
      "files": {}, 
      "form": {
        "a": "1", 
        "b": "1"
      }, 
      "headers": {
        "Accept-Encoding": "gzip", 
        "Content-Length": "7", 
        "Content-Type": "application/x-www-form-urlencoded", 
        "Host": "www.httpbin.org", 
        "User-Agent": "okhttp/4.9.0", 
        "X-Amzn-Trace-Id": "Root=1-6230a7be-57940c9a7c29181744eae16c"
      }, 
      "json": null, 
      "origin": "117.143.100.243", 
      "url": "https://www.httpbin.org/post"
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Post异步请求

请求代码

public void post2(View view) {
        FormBody formBody = new FormBody.Builder()
                .add("a","1")
                .add("b","1")
                .build();
        Request request = new Request.Builder()
                .url("https://www.httpbin.org/post")
                .post(formBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()){
                    Log.i("test",response.body().string());
                }
            }
        });
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

响应内容

I/test: {
      "args": {}, 
      "data": "", 
      "files": {}, 
      "form": {
        "a": "1", 
        "b": "1"
      }, 
      "headers": {
        "Accept-Encoding": "gzip", 
        "Content-Length": "7", 
        "Content-Type": "application/x-www-form-urlencoded", 
        "Host": "www.httpbin.org", 
        "User-Agent": "okhttp/4.9.0", 
        "X-Amzn-Trace-Id": "Root=1-6230a7d8-16dd1aa30c975a7d691c67b6"
      }, 
      "json": null, 
      "origin": "117.143.100.243", 
      "url": "https://www.httpbin.org/post"
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Post上传多个文件

常见文件格式
https://www.runoob.com/http/http-content-type.html

常见的媒体格式类型如下:

text/html : HTML格式
text/plain :纯文本格式
text/xml : XML格式
image/gif :gif图片格式
image/jpeg :jpg图片格式
image/png:png图片格式
以application开头的媒体格式类型:

application/xhtml+xml :XHTML格式
application/xml: XML数据格式
application/atom+xml :Atom XML聚合格式
application/json: JSON数据格式
application/pdf:pdf格式
application/msword : Word文档格式
application/octet-stream : 二进制流数据(如常见的文件下载)
application/x-www-form-urlencoded : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)
另外一种常见的媒体格式是上传文件之时使用的:

multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

请求代码

public void uploadFile(View view) {
        File file1 = new File("E:\\FileTest\\001.jpg");
        File file2 = new File("E:\\FileTest\\002.jpg");
        RequestBody body1 = RequestBody.create(file1, MediaType.parse("image/jpeg"));
        RequestBody body2 = RequestBody.create(file2, MediaType.parse("image/jpeg"));
        MultipartBody multipartBody = new MultipartBody.Builder()
                .addFormDataPart("图片1", file1.getName(), body1)
                .addFormDataPart("图片2", file2.getName(), body2)
                .addFormDataPart("test","test")
                .build();
        Request request = new Request.Builder()
                .url("https://www.httpbin.org/post")
                .post(multipartBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()){
                    Log.i("test",response.body().string());
                }
            }
        });
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/413559?site
推荐阅读
相关标签