Android okhttp使用的方法

所属分类: 软件编程 / Android 阅读数: 32
收藏 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 byte[] 和short[]转换的方法代码

这篇文章主要介绍了android byte[] 和short[]转换的方法代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

Android获取应用程序大小的方法

这篇文章主要介绍了Android获取应用程序大小的方法,有需要的朋友可以参考一下
收藏 0 赞 0 分享

Android获取其他包的Context实例代码

这篇文章主要介绍了Android获取其他包的Context实例代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

Android放大镜的实现代码

这篇文章主要介绍了Android放大镜的实现代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

Android 读取Properties配置文件的小例子

这篇文章主要介绍了Android 读取Properties配置文件的小例子,有需要的朋友可以参考一下
收藏 0 赞 0 分享

Android通讯录开发之删除功能的实现方法

这篇文章主要介绍了Android通讯录开发之删除功能的实现方法,有需要的朋友可以参考一下
收藏 0 赞 0 分享

使用ViewPager实现android软件使用向导功能实现步骤

现在的大部分android软件,都是使用说明,就是第一次使用该软件时,会出现向导,可以左右滑动,然后就进入应用的主界面了,下面我们就实现这个功能
收藏 0 赞 0 分享

android在异步任务中关闭Cursor的代码方法

android在异步任务中如何关闭Cursor?在我们开发应用的时候,很多时候会遇到这种问题,下面我们就看看代码如何实现
收藏 0 赞 0 分享

Android自定义桌面功能代码实现

android自定义桌面其实很简单,看一个例子就明白了
收藏 0 赞 0 分享

android将图片转换存到数据库再从数据库读取转换成图片实现代码

有时候我们想把图片存入到数据库中,尽管这不是一种明智的选择,但有时候还是不得以会用到,下面说说将图片转换成byte[]数组存入到数据库中去,并从数据库中取出来转换成图像显示出来
收藏 0 赞 0 分享
查看更多