OkHttp接入、简单使用、封装

一、接入

先看文档okhttp

接入方式

1-maven

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>3.11.0</version>
</dependency>

2-gradle

implementation 'com.squareup.okhttp3:okhttp:3.11.0'

Android开发一般用这个

3-下载

下载路径:https://search.maven.org/remote_content?g=com.squareup.okhttp3&a=okhttp&v=LATEST
这个不建议

二、使用

请求一般分为get post 两种方式,下面一一说

1.get

// 初始化
OkHttpClient client = new OkHttpClient();

        String url = "";
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response result = null;
        try {
        	// 同步
            result = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (result.isSuccessful()) {
            try {
                String string = result.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

}

2.post

// 提交json格式,同步
OkHttpClient client = new OkHttpClient();
        String url = "";

        String content = "";

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("key", "value");
            jsonObject.put("key", "value");
            jsonObject.put("key", "value");
            // ...
        } catch (JSONException e) {
            e.printStackTrace();
        }
        content = jsonObject.toString();

        RequestBody body  = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),content);

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .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 {
				if (response.isSuccessful()) {
                    String resule = response.body().string();
                }
            }
        });
// 提交表单格式,异步
OkHttpClient client = new OkHttpClient();
        String url = "";
        RequestBody body = new FormBody.Builder().add("key","value").build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .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 {

            }
        });
}

3.下载

 @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                int progress = (int) msg.obj;
                Log.d(TAG, "handleMessage: progress = "+progress);
            }
        }
    };

    private void downLoad() {
        OkHttpClient client = new OkHttpClient();
        String url = "";
        RequestBody body = new FormBody.Builder().add("key","value").build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            
            @Override
            public void onResponse(Call call, Response response){
                if (response.isSuccessful()) {
                    InputStream is = response.body().byteStream();
                    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                    String name = "downLoadFile.txt";
                    File file = new File(path,name);
                    FileOutputStream fos = null;

                    try {
                        fos = new FileOutputStream(file);
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        len = is.read(bytes);
                        int sum = 0;
                        while (len!=-1){
                            fos.write(bytes);
                            sum += len;

                            Message message = handler.obtainMessage(1);
                            message.obj = sum;
                            handler.sendMessage(message);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
    }

三、封装

没有完美的封装,只有适合自己项目的封装,还是自己去GitHub上找吧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于使用OkHttp进行封装,以下是一个基本的示例: 1. 首先,确保已经在项目中添加了OkHttp的依赖。在build.gradle文件中添加以下代码: ```groovy implementation 'com.squareup.okhttp3:okhttp:4.9.0' ``` 2. 创建一个HttpHelper类来封装OkHttp使用。示例代码如下: ```java import okhttp3.*; import java.io.IOException; public class HttpHelper { private final OkHttpClient client; public HttpHelper() { client = new OkHttpClient(); } public void get(String url, Callback callback) { Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(callback); } public void post(String url, RequestBody requestBody, Callback callback) { Request request = new Request.Builder() .url(url) .post(requestBody) .build(); client.newCall(request).enqueue(callback); } } ``` 3. 现在可以在其他类中使用HttpHelper进行网络请求。以下是一个使用GET请求的示例: ```java import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; import java.io.IOException; public class Main { public static void main(String[] args) { HttpHelper httpHelper = new HttpHelper(); String url = "https://api.example.com/data"; httpHelper.get(url, new Callback() { @Override public void onFailure(Call call, IOException e) { // 处理请求失败的情况 } @Override public void onResponse(Call call, Response response) throws IOException { // 处理请求成功的情况 String responseData = response.body().string(); System.out.println(responseData); } }); } } ``` 以上示例中,我们首先创建了一个HttpHelper实例,然后使用get方法发送GET请求。在回调函数中,可以处理请求成功或失败的情况,并处理返回的响应数据。 对于POST请求,可以使用post方法,并传递一个RequestBody对象作为请求体。具体的请求参数和请求头信息可以根据实际需求进行设置。 这只是一个基本的封装示例,你可以根据自己的项目需求进行更多的定制和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值