zoukankan      html  css  js  c++  java
  • OkHttp3的基本使用

    OkHttp3的基本使用

    转 https://blog.csdn.net/yu805894501/article/details/100670409

    简介
    OKhttp3是一个高效、节省带宽、支持HTTP2的HTTP客户端。
    传送门:
    GitHub:https://github.com/square/okhttp
    官网:https://square.github.io/okhttp/

    引入框架
    在build.gradle(app)中的dependencies节点下添加:
    implementation(“com.squareup.okhttp3:okhttp:4.1.1”)

    dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    //OKhttp
    implementation("com.squareup.okhttp3:okhttp:4.1.1")
    }

    后端环境
    后端我是用Tomcat+sevlet实现的后端服务器,主要代码如下
    MyServlet.class

    package com.dimanche;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import com.google.gson.Gson;
    import com.sun.org.apache.bcel.internal.generic.NEW;

    /**
    * Servlet implementation class MyServlet
    */
    @WebServlet("/MyServlet")
    public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    System.out.println("get请求");
    PrintWriter out = response.getWriter();
    String method = request.getParameter("method");// 获取方法
    User user = new User("111", "test", "test");
    Result result = new Result();
    result.setResult("true");
    result.setObject(user);

    out.println(new Gson().toJson(result));

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    System.out.println("post请求");
    PrintWriter out = response.getWriter();
    String method = request.getParameter("method");// 获取方法
    System.out.println("表单"+method);
    StringBuffer json = new StringBuffer();
    String line = null;
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null) {
    json.append(line);
    }
    System.out.println("字符串"+json.toString());

    // 逻辑操作过程
    // 返回计算结果
    User user = new User("111", "test", "test");
    Result result = new Result();
    result.setResult("true");
    result.setObject(user);
    out.println(new Gson().toJson(result));

    }

    }


    Result.class

    package com.dimanche;

    public class Result {
    String result;
    Object object;
    public String getResult() {
    return result;
    }
    public void setResult(String result) {
    this.result = result;
    }
    public Object getObject() {
    return object;
    }
    public void setObject(Object object) {
    this.object = object;
    }
    }


    User.class

    package com.dimanche;

    public class User {
    private String id;
    private String userName;
    private String userCode;

    public User(String id, String userName, String userCode) {
    this.id = id;
    this.userName = userName;
    this.userCode = userCode;
    }

    public String getId() {
    return id;
    }

    public void setId(String id) {
    this.id = id;
    }

    public String getUserName() {
    return userName;
    }

    public void setUserName(String userName) {
    this.userName = userName;
    }

    public String getUserCode() {
    return userCode;
    }

    public void setUserCode(String userCode) {
    this.userCode = userCode;
    }
    }

    代码已上传百度云:
    链接:https://pan.baidu.com/s/1XgBADUtPruig5wLZkULjTw
    提取码:53e2

    OKhttp的简单使用
    说明
    url地址为:
    public static final String BASE_URL = “http://192.168.18.1:8088/MyJspProject/MyServlet”;
    其中的192.168.18.1:8088为我电脑的ip加端口,你们修改为自己的即可

    使用OKhttp进行异步get请求
    public static void getData(String url) {

    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder()
    .url(url)//值得顶地址
    .get()//指定请求方式
    .build();
    //获取Call对象
    Call call = okHttpClient.newCall(request);
    //开启请求,使用execute时同步请求,使用enqueue时异步请求
    call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
    //访问失败
    Log.e("异步get请求失败", e.getMessage());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
    //访问成功
    Log.e("异步get请求成功", response.body().string());
    }
    });
    }

    使用Post异步提交字符串
    public static void subString(String url) {
    //声明提交的数据类型
    MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
    //声明RequestBody
    RequestBody body = RequestBody.create(mediaType, "我被提交啦,哈哈哈哈");
    //声明OkHTTPClient对象
    OkHttpClient okHttpClient = new OkHttpClient();
    //创建Request对象
    Request request = new Request.Builder()
    .url(url)//指定访问地址
    .post(body)//指定请求方式
    .build();
    //获取Call对象
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
    //访问失败
    Log.e("异步Post请求失败", e.getMessage());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
    //访问成功
    Log.e("异步psot请求成功", response.body().string());
    }
    });
    }

    使用post异步提交表单
    public static void subForm(String url) {
    //创建OKhttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .addInterceptor(new TestInterceptor())
    .build();
    //创建RequestBody,使用FormBody描述请求体
    RequestBody requestBody = new FormBody.Builder()
    .add("method", "login")//添加参数
    .build();
    //创建Request对象
    Request request = new Request.Builder()
    .url(url)//指定地址
    .post(requestBody)//指定访问方式并且加入请求体
    .build();
    //获取Call对象
    Call call = okHttpClient.newCall(request);
    //开始请求
    call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
    Log.e("提交表单失败", "" + e.getMessage());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
    Log.e("提交表单成功", "" + response.body().string());
    }
    });
    }

    其中TestInterceptor为拦截器,代码如下

    package com.dimanche.okhttp3.okhttp;

    import android.util.Log;

    import java.io.IOException;

    import okhttp3.Interceptor;
    import okhttp3.Request;
    import okhttp3.Response;

    /**
    * Created by Dimanche on 2019/7/25.
    * 创建拦截器类并且实现Interceptor接口,重写intercept方法
    */

    public class TestInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
    Request request=chain.request();//获取Request
    String url=request.url().url().toString();
    Log.e("请求的地址:",url);
    return chain.proceed(request);
    }
    }



  • 相关阅读:
    【Hibernate框架】对象的三种持久化状态
    【Mybatis架构】Mapper映射文件中的#{}与${}
    【Mybatis架构】 延迟加载
    IDEA快捷键+使用小技巧
    Aop_AspectJ实现
    Aop_实践篇之过滤器
    Aop_思想篇
    超简单的Springboot中的日志管理配置
    SpringMVC+MYBatis企业应用实战笔记
    Spring学习
  • 原文地址:https://www.cnblogs.com/it-tsz/p/12116010.html
Copyright © 2011-2022 走看看