zoukankan      html  css  js  c++  java
  • OkHttp

    加入OkHttp的依赖

    implementation 'com.google.code.gson:gson:2.8.6'

    创建一个OkHttpClient的实例

    OkHttpClient client = new OkHttpClient();

    发送HTTP请求,build方法之前有很多的连缀可以丰富这个Request对象,比如通过url方法来设置目标的网络地址

    Request request = new Request.Builder()
                            .url(address)
                            .build();
    

    之后调用OkHttpClient的newCall方法来创建一个Call对象,并调用它的execute方法来发送请求并获取服务器返回的数据

    //高版本Android默认禁止Http请求,要放开http请求
    Response response = client.newCall(request).execute();
    

    Response对象就是服务器返回的数据,我们可以使用如下写法来得到返回的具体内容

    //要用.body().string()方法,而不是直接.string()
    String responseData = response.body().string();
    

    发送POST请求

    //构造一个requestBody,填充相关数据
     RequestBody requestBody = new FormBody.Builder()
          .add("username", "root")
          .add("password", "admin")
          .build();
    //发送Post请求
    Request request = new Request.Builder()
          .url("https://www.baidu.com")
          .post(requestBody)
          .build();
    //处理Post请求的回复
    try {
          Response requestAboutPost = client.newCall(request).execute();
          String response = requestAboutPost.body().string();
     } catch (IOException e) {
          e.printStackTrace();
         }
    
    
  • 相关阅读:
    ajax专题
    luogu P1346 电车 最短路
    luogu P1462 通往奥格瑞玛的道路 最短路
    luogu P1328 生活大爆炸版石头剪刀布
    luogu P1315 联合权值 枚举
    luogu P1156 垃圾陷阱 背包问题
    luogu P1217 回文质数 枚举
    luogu P3650 滑雪课程设计 枚举
    luogu1209 修理牛棚 贪心
    luogu P1223 排队接水 贪心
  • 原文地址:https://www.cnblogs.com/ngy-liupeng/p/15244404.html
Copyright © 2011-2022 走看看