OkHttp的基本使用——替代Apache HttpClient

缺乏、安全感 2021-06-24 15:58 540阅读 0赞

http是现在主流应用使用的网络请求方式, 用来交换数据和内容, 有效的使用HTTP可以使你的APP 变的更快和减少流量的使用

OkHttp 是一个很棒HTTP客户端:

  • 支持SPDY, 可以合并多个到同一个主机的请求
  • 使用连接池技术减少请求的延迟(如果SPDY是可用的话)
  • 使用GZIP压缩减少传输的数据量
  • 缓存响应避免重复的网络请求

OkHttp可以替换Apache的HttpClient

OkHttp支持2.3和以上版本,对于java,需要jdk1.7 ,OkHttp需要依赖Okio包

下面上demo

1:使用get方式请求,获取响应

  1. import java.io.IOException;
  2. import okhttp3.OkHttpClient;
  3. import okhttp3.Request;
  4. import okhttp3.Response;
  5. public class GetExample {
  6. OkHttpClient client = new OkHttpClient();
  7. String run(String url) throws IOException {
  8. Request request = new Request.Builder()
  9. .url(url)
  10. .build();
  11. try (Response response = client.newCall(request).execute()) {
  12. return response.body().string();
  13. }
  14. }
  15. public static void main(String[] args) throws IOException {
  16. GetExample example = new GetExample();
  17. String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
  18. System.out.println(response);
  19. }
  20. }

2:使用post向服务器发送请求

  1. import java.io.IOException;
  2. import okhttp3.MediaType;
  3. import okhttp3.OkHttpClient;
  4. import okhttp3.Request;
  5. import okhttp3.RequestBody;
  6. import okhttp3.Response;
  7. public class PostExample {
  8. public static final MediaType JSON
  9. = MediaType.parse("application/json; charset=utf-8");
  10. OkHttpClient client = new OkHttpClient();
  11. String post(String url, String json) throws IOException {
  12. RequestBody body = RequestBody.create(JSON, json);
  13. Request request = new Request.Builder()
  14. .url(url)
  15. .post(body)
  16. .build();
  17. try (Response response = client.newCall(request).execute()) {
  18. return response.body().string();
  19. }
  20. }
  21. String bowlingJson(String player1, String player2) {
  22. return "{'winCondition':'HIGH_SCORE',"
  23. + "'name':'Bowling',"
  24. + "'round':4,"
  25. + "'lastSaved':1367702411696,"
  26. + "'dateStarted':1367702378785,"
  27. + "'players':["
  28. + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
  29. + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
  30. + "]}";
  31. }
  32. public static void main(String[] args) throws IOException {
  33. PostExample example = new PostExample();
  34. String json = example.bowlingJson("Jesse", "Jake");
  35. String response = example.post("http://www.roundsapp.com/post", json);
  36. System.out.println(response);
  37. }
  38. }

发表评论

表情:
评论列表 (有 0 条评论,540人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Okhttp3基本使用

    I.简介 HTTP是现代应用常用的一种交换数据和媒体的网络方式,高效地使用HTTP能让资源加载更快,节省带宽。OkHttp是一个高效的HTTP客户端,它有以下默认特性: