安卓基于okhttp3的基本网络

首先 引入依赖

//依赖
 implementation 'com.squareup.okhttp3:okhttp:3.10.0'
 implementation 'com.google.code.gson:gson:2.8.4'

 添加网络权限


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

 其次

在res创建xml文件命名为network_security_config,
后在清单文件声明:


android:networkSecurityConfig="@xml/network_security_config"
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>
基本get请求
public void getRequest() {
        //客户端
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
 
        //创建请求内容
        final Request request = new Request.Builder()
                .get()
                .url("你的接口地址")
                .build();
 
        //用Client去创建请求任务
        Call call = client.newCall(request);
 
        //异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d(TAG, "onFailure: " + e.toString());
            }
 
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                Log.d(TAG, "onResponse: " + string);
                int code = response.code();
                Log.d(TAG, "onResponse: " + code);
            }
        });
    }
带参数的get请求
public void getParameter() {
 
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
 
        Map<String, String> map = new HashMap<>();
        map.put("keyword", "key");
        map.put("page", "12");
        map.put("order", "0");
 
        StringBuilder sb = new StringBuilder();
        sb.append("?");
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            sb.append(next.getKey());
            sb.append("=");
            sb.append(next.getValue());
            if (iterator.hasNext()) {
                sb.append("&");
            }
        }
        String s = sb.toString();
 
        Log.e(TAG, "----" + s);
        Request request = new Request.Builder()
                .url("你的服务器地址" + s)
                .get()
                .build();
 
 
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, "onFailure: " + e.toString());
            }
 
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.e(TAG, "onResponse: " + response.code());
                Log.e(TAG, "onResponse: " + response.body().string());
            }
        });
 
    }
post请求方法带参数
public void postParameter() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000,TimeUnit.MILLISECONDS)
                .build();
 
 
        FormBody.Builder builder = new FormBody.Builder();
 
        RequestBody requestBody = builder
                .add("userName","123")
                .add("password","123456")
                .build();
 
        Request request = new Request.Builder()
                .url("你的服务器地址")
                .post(requestBody)
                .build();
 
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, "onFailure: " + e.toString());
            }
 
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.e(TAG, "onResponse: " + response.code());
                Log.e(TAG, "onResponse: " + response.body().string());
            }
        });
 
 
    }

post对象提交

public void postComment() {
        //客户端
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
 
        //提交内容
        CommandItem commandItem = new CommandItem("123456", "hello!");
        Gson gson = new Gson();
        String jsonstr = gson.toJson(commandItem);
 
        MediaType mediaType = MediaType.parse("application/json");
 
        RequestBody requestBody = RequestBody.create(jsonstr, mediaType);
 
        final Request request = new Request.Builder()
                .url("你的服务器地址")
                .post(requestBody)
                .build();
 
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, "onFailure: " + e.toString());
            }
 
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int code = response.code();
                Log.e(TAG, "onResponse: " + code);
                if (code == HTTP_OK) {
                    ResponseBody body = response.body();
                    Log.e(TAG, "onResponse: " + body.string());
                }
            }
        });
    }

上传单文件

public void postFile() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000,TimeUnit.MILLISECONDS)
                .build();
 
        File file = new File("/storage/self/primary/Download/u=2604811881,2055398559&fm=173&app=49&f=JPEG.jpg");
        MediaType mediaType = MediaType.parse("image/png");
        RequestBody filebody = RequestBody.create(file,mediaType);
 
        RequestBody requestBody = new MultipartBody.Builder()
                .addFormDataPart("file",file.getName(),filebody)
                .build();
 
        Request request = new Request.Builder()
                .url("你的服务器地址")
                .post(requestBody)
                .build();
 
        Call call = client.newCall(request);
 
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, "onFailure: "+e.toString() );
            }
 
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int code = response.code();
                Log.e(TAG, "onResponse: "+code);
                if (code == HTTP_OK){
 
                    Log.e(TAG, "onResponse: "+response.body().string() );
                }
            }
        });
    }

下载文件

public void DownloadFiles() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000,TimeUnit.MILLISECONDS)
                .build();
 
        Request request = new Request.Builder()
                .url("你的服务器地址")
                .get()
                .build();
 
        final Call call = client.newCall(request);
        new Thread(new Runnable() {
            @Override
            public void run() {
                InputStream inputStream = null;
                FileOutputStream fos = null;
                try {
                    Response execute = call.execute();
                    Headers headers = execute.headers();
                    for (int i = 0; i < headers.size(); i++) {
                        Log.e(TAG, "run: "+headers.name(i) + " "+headers.value(i));
                    }
 
                    String contentType = headers.get("Content-disposition");
                    String fileName = contentType.replace("attachment; filename=", "");
                    File outFile = new File(OkhttpActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES)+ File.separator+fileName);
                    if (outFile.getParentFile().exists()) {
                        outFile.mkdirs();
                    }
                    if(!outFile.exists()){
                        outFile.createNewFile();
                    }
 
                    fos = new FileOutputStream(outFile);
 
                    if (execute.body()!=null) {
                        inputStream = execute.body().byteStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = inputStream.read(buffer,0,buffer.length))!=-1){
                            fos.write(buffer,0,len);
                        }
                        fos.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if (inputStream!=null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
 
                    if (fos!=null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
 
            }
        }).start();
 
    }
}

网络请求简单封装:

一、

public abstract class ResultCallback {
    public abstract void onError(Request request, Exception e);
 
    public abstract void onResponse(String str) throws IOException;
}

二、

public class OkhttpUtil {
    private static volatile OkhttpUtil mInstance;
    private OkHttpClient mOkHttpClient;
    private Handler mHandler;
 
    public static OkhttpUtil getInstance() {
        if (mInstance == null) {
            synchronized (OkhttpUtil.class) {
                if (mInstance == null) {
                    mInstance = new OkhttpUtil();
                }
            }
        }
        return mInstance;
    }
 
    private OkhttpUtil() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .readTimeout(1000, TimeUnit.MILLISECONDS)
                .connectTimeout(1000,TimeUnit.MILLISECONDS);
        mOkHttpClient = builder.build();
        mHandler = new Handler();
    }
 
    public void getAsynHttp(String url, ResultCallback callback) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = mOkHttpClient.newCall(request);
        dealResult(call, callback);
    }
 
    private void dealResult(Call call, final ResultCallback callback) {
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                sendFailedCallback(call.request(), e, callback);
            }
 
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                sendSuccessCallback(response.body().string(), callback);
            }
        });
    }
 
    private void sendSuccessCallback(final String string, final ResultCallback callback) throws IOException {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    callback.onResponse(string);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
 
    private void sendFailedCallback(final Request request, final IOException e, final ResultCallback callback) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onError(request, e);
                }
            }
        });
    }
 
 
}

简单使用:

OkhttpUtil okhttpUtil = OkhttpUtil.getInstance(BaseApplication.getContext());
        okhttpUtil.getAsynHttp(url, new ResultCallback() {
            @Override
            public void onError(Request request, Exception e) {
                Log.e(TAG, "onFailure: " + e.toString());
                
            }
 
            @Override
            public void onResponse(String str) throws IOException {
                
            }
        });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来之梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值