OkHttp3 框架学习

1.Okhttp介绍
android网络框架Okhttp,是轻量级框架,由移动支付Square公司贡献
优点:
允许连接到同一个主机地址的所有请求,提高请求效率
共享Socket,减少对服务器的请求次数
通过连接池,减少了请求延迟
缓存响应数据来减少重复的网络请求
减少了对数据流量的消耗
自动处理GZip压缩
功能:
get,post请求
文件的上传下载
加载图片
支持请求回调,直接返回对象、对象集合
支持session的保持
2.开源项目地址
https://github.com/square/okhttp
下载
# git clone https://github.com/square/okhttp.git
在build.gradle(Module:app)中增加
dependencies {
 implementation 'com.squareup.okhttp3:okhttp:3.9.1'
}

3.核心类
1)OkHttpClient创建OkHttpCLient对象
OkHttpClient client = new OkHttpClient();
2)Request
构造一个Request对象
通过Request.BUilder()设置参数,默认的是get请求
Request request = new Request.Builder()
                        .url(url)
                        .build();
3)通过request对象去构造一个Call对象,将请求封装成了任务
用call.enqueue异步去执行请求,将call加入调度队列,在Callback中即可得到结果
client.newCall(request).enqueue(new Callback()

请求网络的时候我们需要用OkHttpClient.newCall(request)进行execute或者enqueue操作

4)回调结果onResponse
@Override
public void onResponse(Call call, Response response) throws IOException {
                       final String str = response.networkResponse().toString();
                        
});
onResponse回调的参数是response,一般情况下,比如我们希望获得返回的字符串,可以通过
response.body().string()获取;如果希望获得返回的二进制字节数组,则调用
response.body().bytes();如果你想拿到返回的inputStream,则调用
response.body().byteStream()
5)post请求传参时构造RequestBody
 RequestBody fromBody = new FormBody.Builder()
                        .add("key","8db57b752c2b47599348865ccfd30ba4")
                        .add("location","成都")
                        .build();
post(fromBody);

能过POST方式把键值对数据传送到服务器,post提交键值对比get方法多了一个RequestBody
//提交Json数据
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    
    
     OkHttpClient client = new OkHttpClient();
     RequestBody body = RequestBody.create(JSON, json);
     Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
------------------------------------------------------------------------------------------------------

4.Demo


public class MainActivity extends AppCompatActivity {
    private Button btGet;
    private Button btPost;
    private Button btFileDownload;
    private Button btUpload;
    private Button btPicture;
    private ImageView iv;
 
    private TextView tv;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        btGet = (Button)findViewById(R.id.btGet);
        btPost = (Button)findViewById(R.id.btPost);
        btFileDownload = (Button)findViewById(R.id.btFileDownload);
        btUpload = (Button)findViewById(R.id.btUpload);
        btPicture = (Button)findViewById(R.id.btPicture);
        iv = (ImageView)findViewById(R.id.imageView);
 
        tv = (TextView)findViewById(R.id.textView);
 
        //异步Get
        btGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url ="https://www.baidu.com";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
 
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
 
                    }
 
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                       //请求网页的内容
                        final String str = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv.setText(str);
                            }
                        });
                    }
                });
            }
        });
 
        //异步POST请求
        //注册一个和风的账号https://www.heweather.com/
        //可以获取一个key,根据key,和location可以查询weather
        btPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url ="https://free-api.heweather.com/s6/weather";
                OkHttpClient client = new OkHttpClient();
                RequestBody fromBody = new FormBody.Builder()
                        .add("key","8db57b752c2b47599348865ccfd30ba4")
                        .add("location","成都")
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .post(fromBody)
                        .build();
 
                client.newCall(request)
                        .enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                Log.i("tag","post fail");
                            }
 
                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                final String str = response.body().string();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        tv.setText(str);
                                    }
                                });
                            }
                        });
            }
        });
        //异步文件下载
        //下载一张图片,将流写进指定的图片文件中
        btFileDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url ="http://192.168.42.218:8080/flower.jpeg";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request
                        .Builder()
                        .url(url)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv.setText("文件下载失败");
                            }
                        });
 
                    }
 
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //把请求成功的response转为字节流
                        InputStream inputStream = response.body().byteStream();
                        FileOutputStream fileOutputStream = null;
                        try{
                            fileOutputStream = new FileOutputStream(
                                    new File("/mnt/sdcard/test.jpeg"));
                            byte[] buffer = new byte[2048];
                            int len = 0;
                            while((len=inputStream.read(buffer))!= -1){
                                fileOutputStream.write(buffer,0,len);
                            }
                            fileOutputStream.flush();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tv.setText("文件下载成功");
                                }
                            });
 
                        }catch (IOException e){
                            e.printStackTrace();
                        }
 
                    }
                });
            }
        });
        //异步上传文件
        btUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url ="http://192.168.42.218:8080/";
                File file = new File("/mnt/sdcard/wifi");
                OkHttpClient client = new OkHttpClient();
                Request request = new Request
                        .Builder()
                        .url(url)
                        .post(RequestBody.create(MediaType.parse("application/octet-stream"), file))
                        .build();
                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() {
                                    tv.setText("上传成功:"+response.body().toString());
                                }
                            });
                            }
                        });
            }
        });
        //图片下载并显示到imageView中
        btPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "http://192.168.42.218:8080/flower.jpeg";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request
                        .Builder()
                        .url(url)
                        .build();
                client.newCall(request)
                        .enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
 
                            }
 
                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                //获取流
                                InputStream in = response.body().byteStream();
                                //转化为bitmap
                                final Bitmap bitmap = BitmapFactory.decodeStream(in);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        iv.setImageBitmap(bitmap);
                                    }
                                });
                            }
                        });
            }
        });
    }
}
参考:
http://www.heweather.com/
http://blog.csdn.net/lmj623565791/article/details/47911083
http://blog.csdn.net/itachi85/article/details/51190687

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OKHttp是一个开源的HTTP客户端框架,用于Android平台的网络请求。它提供了简洁的API和强大的功能,使得在Android应用中进行网络请求变得更加方便和高效。 使用OKHttp可以发送HTTP请求、接收和解析服务器响应、处理网络错误等。它支持GET、POST、PUT、DELETE等常见的HTTP方法,并且可以设置请求头、请求体、超时时间等。此外,OKHttp还支持文件上传和下载,以及WebSocket协议。 在Android开发中,你可以通过添加OKHttp库的依赖,然后在代码中创建OKHttp的实例,使用它来发送网络请求。下面是一个简单的示例: ```java // 添加OKHttp库的依赖 implementation 'com.squareup.okhttp3:okhttp:4.9.1' // 创建OKHttp实例 OkHttpClient client = new OkHttpClient(); // 创建请求对象 Request request = new Request.Builder() .url("http://www.example.com/api/data") .build(); // 发送异步请求 client.newCall(request).enqueue(new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { // 处理服务器响应 String responseData = response.body().string(); // ... } @Override public void onFailure(Call call, IOException e) { // 处理网络错误 e.printStackTrace(); // ... } }); ``` 以上代码中,首先添加了OKHttp库的依赖。然后创建了一个OKHttpClient实例,用于发送请求。接着创建了一个Request对象,设置了请求的URL。最后通过调用`client.newCall(request).enqueue()`方法发送异步请求,并在回调方法中处理服务器响应和网络错误。 需要注意的是,网络请求应该在后台线程中执行,以避免阻塞主线程。你可以使用`AsyncTask`、`Thread`或者`Coroutine`等方式来实现在后台线程中执行网络请求。 当然,OKHttp还有更多的功能和用法,例如设置请求参数、请求拦截器、HTTPS支持等。你可以查阅官方文档或其他资源来深入学习和使用OKHttp。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值