美文网首页
Okhttp3 如何发送请求?

Okhttp3 如何发送请求?

作者: 孤独狂饮 | 来源:发表于2017-08-17 15:23 被阅读1310次

最近研究 Okhttp3, 把项目 down 下来后,发现不能编译,真实尴尬。平时使用的都是 gradle, 但是该项目使用 maven,导入 idea 后,摸索两下,用界面的命令行搞起。

image.png

项目中有好多 model, 本次主要看看 Okhttp3 的 get/post 请求。其实我们自己很容易就能写出来,不过还是看看 官方 demo 的写法吧。

get 请求

public class GetExample {
  OkHttpClient client = new OkHttpClient();

  String run(String url) throws IOException {
    Request request = new Request.Builder()
        .url(url)
        .build();

    try (Response response = client.newCall(request).execute()) {
      return response.body().string();
    }
  }

  public static void main(String[] args) throws IOException {
    GetExample example = new GetExample();
    String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
    System.out.println(response);
  }
}

这个里面需要提到的是 try(需要一次捕获的代码){正常后处理的代码} 这是 java 7.0 以上的 try catch 结构,操作方便。

post 请求


public class PostExample {
  public static final MediaType JSON
      = MediaType.parse("application/json; charset=utf-8");

  OkHttpClient client = new OkHttpClient();

  String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    try (Response response = client.newCall(request).execute()) {
      return response.body().string();
    }
  }

  String bowlingJson(String player1, String player2) {
    return "{'winCondition':'HIGH_SCORE',"
        + "'name':'Bowling',"
        + "'round':4,"
        + "'lastSaved':1367702411696,"
        + "'dateStarted':1367702378785,"
        + "'players':["
        + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
        + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
        + "]}";
  }

  public static void main(String[] args) throws IOException {
    PostExample example = new PostExample();
    String json = example.bowlingJson("Jesse", "Jake");
    String response = example.post("http://www.roundsapp.com/post", json);
    System.out.println(response);
  }
}

重点在这里『RequestBody.create(JSON, json)』, 构建 post 的 body 的时候,直接传入 mediaType 和 json 内容即可构建成功。

下面还有好多,可以直接在 github 上查看:

image.png

异步 get 请求,猜猜结果是什么?


public final class AsynchronousGet {
  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

    client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
        e.printStackTrace();
      }

      @Override public void onResponse(Call call, Response response) throws IOException {
        try (ResponseBody responseBody = response.body()) {
          if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

          Headers responseHeaders = response.headers();
          for (int i = 0, size = responseHeaders.size(); i < size; i++) {
            System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
          }

          System.out.println(responseBody.string());
        }
      }
    });
    System.out.println(" 异步了么?");
  }

  public static void main(String... args) throws Exception {
    new AsynchronousGet().run();
  }
}

结果亮起来了:

image.png

需要用户登录后才能访问接口

我们 尝试直接访问 http://publicobject.com/secrets/hellosecret.txt , 会强制我们登录,否则就没有返回值。
登录名: jesse
登陆密码: password1

会看到 android 的密钥哈

public final class Authenticate {
  private final OkHttpClient client;

  public Authenticate() {
    client = new OkHttpClient.Builder()
        .authenticator(new Authenticator() {
          @Override public Request authenticate(Route route, Response response) throws IOException {
            if (response.request().header("Authorization") != null) {
              return null; // Give up, we've already attempted to authenticate.
            }

            System.out.println("Authenticating for response: " + response);
            System.out.println("Challenges: " + response.challenges());
            String credential = Credentials.basic("jesse", "password1");
            return response.request().newBuilder()
                .header("Authorization", credential)
                .build();
          }
        })
        .build();
  }

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/secrets/hellosecret.txt")
        .build();

    try (Response response = client.newCall(request).execute()) {
      if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

      System.out.println(response.body().string());
    }
  }

  public static void main(String... args) throws Exception {
    new Authenticate().run();
  }
}

相关文章

  • Okhttp3 如何发送请求?

    最近研究 Okhttp3, 把项目 down 下来后,发现不能编译,真实尴尬。平时使用的都是 gradle, 但是...

  • OkHttp3 HTTP请求执行流程分析

    OkHttp3的基本用法 使用OkHttp3发送Http请求并获得响应的过程大体为: 创建OkHttpClient...

  • 获取请求的参数

    发送请求----发送带参数的请求----获取请求参数 如何发送请求 发送请求格式:域名/模块/控制器/方法名模块是...

  • 处理用户发送的get和post请求

    如何处理用户发送的get请求 如何处理用户发送的post请求

  • Retrofit,源码简单分析

    场景 Retrofit + Okhttp3 是现在开发标配的网络请求框架Okhttp3 负责底层请求逻辑Ret...

  • AJAX

    1. 如何发送请求 通过form表单发送请求(包括get请求和post请求),会刷新页面或新开页面 通过a链接发送...

  • node.js处理post请求

    注意:浏览器只能发送get请求,那如何发送post请求呢?发送post请求可以手写ajax请求,但是有跨域问题!所...

  • Retrofit2源码解析

    Retrofit网络请求的功能实现是okhttp3,由okhttp3做真正的网络请求。Retrofit2框架和其他...

  • OkHttp3源码解析(一)之请求流程

    本文基于OkHttp3的3.11.0版本 OkHttp3发起请求方式 我们用OkHttp3发起一个网络请求一般是这...

  • JAVA服务通过URL下载文件

    概述 如何通过Java发送HTTP请求,通俗点讲,如何通过Java(模拟浏览器)发送HTTP请求。 Java有原生...

网友评论

      本文标题:Okhttp3 如何发送请求?

      本文链接:https://www.haomeiwen.com/subject/svxnrxtx.html