Android okhttp使用的方法

所属分类: 软件编程 / Android 阅读数: 51
收藏 0 赞 0 分享

简介

OKHttp是一个十分常用的网络请求框架了,用于android中请求网络。

除了OKHttp,如今Android中主流的网络请求框架有:

  • Android-Async-Http
  • Volley
  • OkHttp
  • Retrofit

依赖库导入

在build.gradle 添加如下依赖

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

添加网络权限

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

get请求

/**
 *  同步Get同求
 *
 * @param url url
 * @return
 */
public String syncGet(String url) {
    String result = "";
    //1.创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder()
            .url(url)
            .get()
            .build();
    final Call call = okHttpClient.newCall(request);
        //4.同步调用会阻塞主线程,这边在子线程进行
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //同步调用,返回Response,会抛出IO异常
                    Response response = call.execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();



    return result;
}

/**
 *  异步Get同求
 *
 * @param url url
 * @return
 */
public void nonSyncGet(String url, Callback responseCallback) {
    String result = null;
    //1.创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient();
    //2.创建Request对象
    Request request = new Request.Builder()
            .url(url)
            .get()
            .build();
    Call call =okHttpClient.newCall(request);
    call.enqueue(responseCallback);
}

Post请求

在OkHttp中用Post方法把键值对数据传送到服务器,使用FormBody.Builder创建请求的参数键值,构建一个RequestBody对象,

  • key-value:提交键值对
  • String:字符串类型
  • Form:表单数据
  • Stream:流类型
  • File:文件类型
/**
 * 同步Post同求
 *
 * @param url url
 * @return
 */
public String syncPost(String url) {
    String result = null;
    //1.创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient();

    FormBody.Builder mBuild = new FormBody.Builder();
    mBuild.add("name", "tony")
            .add("age", "21");
    RequestBody requestBody= mBuild.build();
    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Response response = null;
    try {
        response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            result = response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

/**
 * 异步Post同求
 *
 * @param url url
 * @return
 */
public void nonSyncPost(String url, Callback responseCallback) {
    //1.创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient();
    FormBody.Builder mBuild = new FormBody.Builder();
    mBuild.add("name", "tony")
            .add("age", "21");
    RequestBody requestBody= mBuild.build();
    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    try {
        okHttpClient.newCall(request).enqueue(responseCallback);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
/**
 * Post json
 *
 * @param url url
 * @return
 */
public String postJson(String url, Callback responseCallback) {
    String result = null;
    String jsonStr = "json";
    //1.创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient();
    MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
    RequestBody requestBody = RequestBody.create(mediaType, jsonStr);
    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Response response = null;
    try {
        response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            result = response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

/**
 * Post String
 *
 * @param url url
 * @return
 */
public String postString(String url, Callback responseCallback) {
    String result = null;
    //1.创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"),
            "{username:tony;password:123456}");
    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Response response = null;
    try {
        response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            result = response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

post表单请求

/**
 * Post 表单
 *
 * @param url url
 * @return
 */
public String postForm(String url, Callback responseCallback) {
    String result = null;
    //1.创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient();
    MultipartBody.Builder mBuild = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("username", "tony")
            .addFormDataPart("password", "123456");
    RequestBody requestBody= mBuild.build();
    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Response response = null;
    try {
        response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            result = response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

post 上传文件

public void uploadFile(String url) {
    ArrayList<String> filelist = getFileList();
    //1.创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient();
    MultipartBody.Builder multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
    for (int i = 0; i < filelist.size(); i++) {
        String path = filelist.get(i);
        File file = new File(path);
        String fileMimeType = getMimeType(file);
        //这里获取文件类型,方法自己定义
        MediaType mediaType = MediaType.parse(fileMimeType);
        RequestBody fileBody = RequestBody.create(mediaType, file);
        multipartBody.addFormDataPart("file" + i, file.getName(), fileBody);
    }
    RequestBody requestBody = multipartBody.build();
    Request requestPostFile = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Response response = null;
    try {
        response = okHttpClient.newCall(requestPostFile).execute();
        if (response.isSuccessful()) {
        } else {
            throw new IOException("Unexpected code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

参考博文

https://www.jianshu.com/p/bb57bc65e4ce

https://www.jianshu.com/p/b1cf0b574e74

更多精彩内容其他人还在看

Android样式和主题之选择器的实例讲解

今天小编就为大家分享一篇关于Android样式和主题之选择器的实例讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

Android应用动态修改主题的方法示例

今天小编就为大家分享一篇关于Android应用动态修改主题的方法示例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

Flutter 网络请求框架封装详解

这篇文章主要介绍了Flutter 网络请求框架封装详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Flutter倒计时/计时器的实现代码

这篇文章主要介绍了Flutter倒计时/计时器的实现代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Android使用google breakpad捕获分析native cash

这篇文章主要介绍了Android使用google breakpad捕获分析native cash 的相关知识,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

详解Flutter WebView与JS互相调用简易指南

这篇文章主要介绍了详解Flutter WebView与JS互相调用简易指南,分为JS调用Flutter和Flutter调用JS,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Android开发实现ListView和adapter配合显示图片和文字列表功能示例

这篇文章主要介绍了Android开发实现ListView和adapter配合显示图片和文字列表功能,涉及Android使用ListView结合adapter适配器实现图文显示功能相关的布局、解析、权限控制等操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Android文字基线Baseline算法的使用讲解

今天小编就为大家分享一篇关于Android文字基线Baseline算法的使用讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

Flutter自定义实现神奇动效的卡片切换视图的示例代码

这篇文章主要介绍了Flutter自定义实现神奇动效的卡片切换视图的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Android实现自定义滑动刻度尺方法示例

这篇文章主要给大家介绍了关于Android实现自定义滑动刻度尺的相关资料,文中通过示例代码介绍的非常详细,对各位Android开发者们具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
收藏 0 赞 0 分享
查看更多