Android框架之OKHttp(1)

Android框架之OKHttp

概念

一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso)用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient,现在已经打不出来)

本文介绍的是原生OKHttp的GET、POST小案例,用法相对麻烦,又必须了解下。现在有封装好了的OKHttp的库,后面在做介绍。欢迎大家关注一下我的博客。

希望我代码不对的地方,或者有更好的代码,大家可以指出来,让我学习,一起进步!谢谢大家!

优势

支持连接同一地址的链接共享同一个socket

通过连接池来减少相应延迟

透明的GZIP压缩

主要功能

联网请求文本数据

大文件上传

大文件下载

请求图片

使用步骤

本文简单介绍其GET、POST请求,更多案列,之后在于大家分享!博客连续更新中,大家可以关注下!本人使用的是Android studio

1、下载OKHttp3
打开Project Structure(ctrl+alt+shift+s)
在这里插入图片描述
选择Dependencies,添加依赖,点击小加号进行添加
在这里插入图片描述
输入OKHttp进行查找之后选择版本,点击OK等待Android studio下载完成

在这里插入图片描述如果下载不了,可以下载JAR包进行添加,自行百度,这里不做介绍了。

添加网络权限
在这里插入图片描述

2、同步GET请求
该方法需要在子线程中执行,故要更新组件信息,又要用到 Handler进行更新
具体代码:

package com.example.application;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OKhttpTest extends Activity {
    Button GET;
    TextView tvShow;

    //创建handler对象对TextView tvShow进行信息更新
  Handler  handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
if(msg.what == 1){
    tvShow.setText(msg.obj.toString());  //更新组件
}
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GET=findViewById(R.id.but_GET);
        tvShow = findViewById(R.id.tv_show);

        GET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    GET("https://www.baidu.com/");      //用自定义方法GET(string url);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
 /*******************************************************/
    private void GET(final String url) throws IOException {
        new Thread(){                                          //开启线程
            @Override
            public void run() {
                super.run();
                OkHttpClient client = new OkHttpClient();  //创建客户端
                Request request = new Request
                        .Builder()
                        .url(url)
                        .build();
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    String str= response.body().string();        //这里用的是string 不是tostring
                    //用msg与handler进行组件信息更新
                    Message msg = new Message();
                    msg.what=1;
                    msg.obj = str;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();   //开启线程

    }
}

3、异步GET请求
异步比同步常用

package com.example.application;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.Nullable;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class OKhttpTest extends Activity {
    Button GET;
    TextView tvShow;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GET=findViewById(R.id.but_GET);
        tvShow = findViewById(R.id.tv_show);

        GET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    GET("https://www.baidu.com/");      //用自定义方法GET(string url);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void GET(final String url) throws IOException {
                OkHttpClient client = new OkHttpClient();  //创建客户端
                Request request = new Request.Builder().url(url).build();
        Call call = client.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()){
            final String str = response.body().string();
           tvShow.post(new Runnable() {    //更新tvShow
               @Override
               public void run() {
                    tvShow.setText(str);
               }
           });
        }
    }
});
}
}

实现图:
实用中并不会获取这些乱七八糟的数据
在这里插入图片描述

4、POST请求
可以用于得到数据,也可以用于上传数据

与GET同步请求差不多,也用在子线程中执行
大致步骤如下:

package com.example.application;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OKhttpTest extends Activity {
    public static final MediaType JSON
            = MediaType.get("application/json; charset=utf-8");  //配置文件
    Button POST;
    TextView tvShow;

    //创建handler对象对TextView tvShow进行信息更新
    Handler  handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                tvShow.setText(msg.obj.toString());  //更新组件
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        POST=findViewById(R.id.but_POST);
        tvShow = findViewById(R.id.tv_show);

        POST.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    POST("https://www.baidu.com/","");  //不是上传数据故为空
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /*******************************************************/
    private void POST(final String url, final String json) throws IOException {
        new Thread(){                                          //开启线程
            @Override
            public void run() {
                super.run();
                OkHttpClient client = new OkHttpClient();  //创建客户端
                RequestBody body =RequestBody.create(json,JSON);
                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    String str = response.body().string();
                    //用msg与handler进行组件信息更新
                    Message msg = new Message();
                    msg.what=1;
                    msg.obj = str;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }
}

总结

我例子中的百度官网,这里只是简单的演示,使用中并不会这么用来获得这些乱七八糟的数据。
本人新手,希望大家对我的文章进行斧正,谢谢大家了!

猜你喜欢

转载自blog.csdn.net/weixin_44758662/article/details/107805285