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();
         }
    
    
  • 相关阅读:
    LeetCode --- Roman to Integer
    LeetCode --- Maximum Depth of Binary Tree
    LeetCode --- Minimum Path Sum
    Hashkell 第一篇
    LeetCode --- Partition List
    LeetCode --- Valid Palindrome
    LeetCode --- Longest Consecutive Sequence
    LeetCode --- Insertion Sort List
    数据库lib7第2, 3题(创建索引和触发器)
    LeetCode --- Reverse Integer
  • 原文地址:https://www.cnblogs.com/ngy-liupeng/p/15244404.html
Copyright © 2011-2022 走看看