Android OkHttp有关GET、POST、MultiPart、及解析json数据的应用

Android OkHttp的GET和POST使用

常见的网络请求:

  • GET
  • 普通POST form请求
  • 支持文件上传的POST form请求
  • POST json字符串

Android网络请求注意事项

使用HTTPS协议的URL

   如果是CA签发的,一般情况下,直接访问即可;
   如果是自签的,访问前需要设置SSL相关配置;

使用HTTP协议的URL

  从Android P开始,默认不再允许直接访问HTTP请求;
  通过设置Network Security Configuration支持;

主要网络访问框架:OkHttp

OkHttp的开源地址

OkHttp的下载地址
注意事项:
OkHttp 3.12.x支持Android 2.3,Java7;
OkHttp最新版本4.3.1要求Android5.0,Java 8

OkHttp使用流程

  • 创建请求:Request.Builder() - > Request对象
  • 通过Request得到Call对象:client.newCall(request) ->Call对象
  • 执行Call:同步call.execute(),异步call.enqueue()
  • 得到Response对象

OkHttp拦截器

  • 了解OkHttp拦截器
  • 引入官方logging-interceptor,打印请求的详细信息
  • 自定义拦截器,对每个请求添加作者,时间戳等信息

下面通过一个实例来讲述基于OkHttp的GET和POST使用
1.下载OkHttp的jar包
有两种方式:
①直接下载OkHttp的jar包
点此下载OkHttp的jar包
②直接在Android studio的build.grale中添加编译

implementation("com.squareup.okhttp3:okhttp:4.3.1")

在这里插入图片描述
注意添加编译代码的位置!!!
2.添加网络权限

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

在这里插入图片描述
注意添加网络权限代码的位置!!!
3.GET请求
创建OkHttpUtils 实体类
声明OkHttpUtils 空的构造方法

 private OkHttpUtils(){
   

    }

创建INetCallBack接口

package rj19.bh.okhttpretrofit0420.net.okhttp;

public interface INetCallBack {
   
    void onSuccess(String response);
    void onFailed(Throwable ex);
}

创建doGet方法

 public String doGet(String url){
   
        try {
   
            //1-获取OkHttpClient对象
            OkHttpClient client = new OkHttpClient();
            //2-创建Request对象
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            //3-创建call对象
            Call call =  client.newCall(request);
            //4-调用call对象的execute(同步)发送请求、enqueue(异步)发送请求 此处为同步
            Response response = call.execute();
            //4-获取response对象中的数据
            return response.body().string();

        } catch (IOException e) {
   
            e.printStackTrace();
        }
        return null;
    }

OkHttpUtils 的完整代码

package rj19.bh.okhttpretrofit0420.net.okhttp;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpUtils {
   
    private OkHttpUtils(){
   

    }
    private static OkHttpUtils sInstance = new OkHttpUtils();

    public static OkHttpUtils getInstance(){
   
        return sInstance;
    }
 // get  http://www.imooc.com/api/okhttp/getmethod?username=hyman
    public String doGet(String url){
   
        try {
   
            //1-获取OkHttpClient对象
            OkHttpClient client = new OkHttpClient();
            //2-创建Request对象
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            //3-创建call对象
            Call call =  client.newCall(request);
            //4-调用call对象的execute(同步)发送请求、enqueue(异步)发送请求 此处为同步
            Response response = call.execute();
            //4-获取response对象中的数据
            return response.body().string();
        } catch (IOException e) {
   
            e.printStackTrace();
        }
        return null;
    }
}

4.添加activity_main.xml页面代码
添加了4个按钮,1个TextView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_get"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="okhttp get 请求"></Button>

    <Button
        android:id="@+id/btn_post"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="okhttp post 请求"></Button>

    <Button
        android:id="@+id/btn_post_multipart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="okhttp post multipart 请求"></Button>

    <Button
        android:id="@+id/btn_post_json"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="okhttp post json 请求"></Button>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

在这里插入图片描述
5.当点击第一个按钮(OkHttp GET请求)时,在TextView处显示获取到的信息
GET请求:
在MainActivity.java中添加第一个按钮的监听事件

 mBtnGet.setOnClickListener(new View.OnClickListener() {
   
            @Override
            public void onClick(View v) {
   
                //发起网络请求
                //http://www.imooc.com/api/okhttp/getmethod?username=hyman
                new Thread(){
   
                    @Override
                    public void run() {
   
                        final String mcontent = OkHttpUtils.getInstance()
                                .doGet("http://www.imooc.com/api/okhttp/getmethod?username=hyman");
                        //因为非UI线程
                        mHandler.post(new Runnable() {
   
                            @Override
                            public void run() {
   
                                content.setText(mcontent);
                            }
                        });
                    }
                }.start()
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值