[关闭]
@File 2019-09-02T07:12:32.000000Z 字数 4209 阅读 139

okhttp

java


四步主要实现过程

一、依赖包

  1. <!-- okhttp3 -->
  2. <dependency>
  3. <groupId>com.squareup.okhttp3</groupId>
  4. <artifactId>okhttp</artifactId>
  5. <version>3.14.2</version>
  6. </dependency>

二、共用实现

GET

  1. // okhttp对象
  2. OkHttpClient okc = new OkHttpClient();
  3. // 获取请求发送对象(GET)
  4. Call call = okc.newCall(
  5. // 请求配置
  6. new Request
  7. .Builder()
  8. .url("http://10.3.135.58:8080/api/company")
  9. .build()
  10. );

POST

1. 获取请求体对象(常用的三个方法)
  • MediaType.parse
    • json : application/json
    • xml : application/xml
    • png : image/png
    • jpg : image/jpeg
    • gif : imge/gif
    • md : text/x-markdown
  1. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "请求内容");
  1. RequestBody requestBody = new RequestBody() {
  2. @Nullable
  3. @Override
  4. public MediaType contentType() {
  5. // 请求内容类型
  6. return MediaType.parse("text/x-markdown; charset=utf-8");
  7. }
  8. @Override
  9. public void writeTo(BufferedSink sink) throws IOException {
  10. // 请求内容
  11. sink.writeUtf8("hello!");
  12. }
  13. };
  1. RequestBody requestBody = new FormBody
  2. .Builder()
  3. .add("key","value")
  4. .add("key","value")
2. 获取请求发送对象
  1. Call call = okc.newCall(
  2. // 请求配置
  3. new Request
  4. .Builder()
  5. .post(requestBody) // 声明请求类型
  6. .url("http://10.3.135.58:8080/api/company")
  7. .build()
  8. );

三、execute() 同步请求

  1. try {
  2. // 发送请求,拿到回调内容对象
  3. ResponseBody resBody = call.execute().body();
  4. // 以字符串形式取出
  5. String resStr = resBody.string();
  6. } catch (IOException e) {
  7. e.printStackTrace();
  8. }

四、enqueue() 异步请求

  1. call.enqueue(new Callback() {
  2. // 请求失败
  3. @Override
  4. public void onFailure(Call call, IOException e) {
  5. // 失败执行的操作
  6. System.out.println(e.getMessage());
  7. }
  8. // 请求成功
  9. @Override
  10. public void onResponse(Call call, Response res) throws IOException {
  11. // 成功执行的操作
  12. System.out.println(res.body().string());
  13. }
  14. });

copy加改

1. 只有 get 和 post 的简单工具类

  1. public class RequestTool {
  2. /**
  3. * get 请求
  4. * @param url 请求地址
  5. * @return 相应内容
  6. * @throws IOException IO异常
  7. */
  8. public static String get(String url) throws IOException {
  9. return respString(url,null);
  10. }
  11. /**
  12. * post 带参请求
  13. * @return 请求对象
  14. */
  15. public static Req post(){
  16. return new Req();
  17. }
  18. /**
  19. * post 请求
  20. * @param url 请求地址
  21. * @return 相应内容
  22. * @throws IOException IO异常
  23. */
  24. public static String post(String url) throws IOException {
  25. return new Req().send(url);
  26. }
  27. /**
  28. * 发起请求,获取相应的字符串
  29. * @param url 请求连接
  30. * @param body 请求体(post才需要)
  31. * @return 相应体对象
  32. * @throws IOException IO异常
  33. */
  34. private static String respString(String url,RequestBody body) throws IOException {
  35. return respBody(url,body).string();
  36. }
  37. /**
  38. * 获取相应体对象
  39. * @param url 请求连接
  40. * @param body 请求体(post才需要)
  41. * @return 相应体对象
  42. * @throws IOException IO异常
  43. */
  44. private static ResponseBody respBody(String url,RequestBody body) throws IOException {
  45. OkHttpClient okc = new OkHttpClient();
  46. Request.Builder request = new Request
  47. .Builder()
  48. .url(url);
  49. if(body != null){
  50. request.post(body);
  51. }
  52. Call call = okc.newCall(request.build());
  53. return call.execute().body();
  54. }
  55. /**
  56. * 请求对象
  57. */
  58. public static class Req{
  59. private MediaType mediaType;
  60. private FormBody.Builder builder;
  61. private File file;
  62. /**
  63. * 给请求体添加参数
  64. * @param key 参数名
  65. * @param value 参数值
  66. * @return 当前请求对象
  67. */
  68. public Req param(String key,String value) {
  69. if(builder == null){builder = new FormBody.Builder();}
  70. builder.add(key,value);
  71. return this;
  72. }
  73. /**
  74. * 发送文件
  75. * @param file 文件对象
  76. * @param mediaType 文件类型
  77. * @return 当前请求对象
  78. */
  79. public Req file(File file,String mediaType){
  80. this.file = file;
  81. this.mediaType = MediaType.parse(mediaType);
  82. return this;
  83. }
  84. /**
  85. * 发送请求
  86. * @return 相应内容
  87. * @throws IOException IO异常
  88. */
  89. public String send(String url) throws IOException {
  90. // 表单
  91. if(builder == null){
  92. return respString(url,builder.build());
  93. }
  94. // 文件
  95. if(file != null && mediaType != null){
  96. return respString(url,RequestBody.create(mediaType,file));
  97. }
  98. // 空请求
  99. return respString(url,RequestBody.create(
  100. MediaType.parse("application/json; charset=utf-8"),
  101. ""
  102. ));
  103. }
  104. }
  105. }

2. 工具栏调用

  1. // get 请求,参数自己拼接到 url 上
  2. String res = RequestTool.get("http://localhost:8080/okhttp/GetReq");
  3. // 无参 post 请求
  4. String res = RequestTool.post("http://localhost:8080/okhttp/PostReq");
  5. // 有参 post 请求
  6. String res = RequestTool
  7. .post()
  8. .param("key","value")
  9. .param("id","10")
  10. .send("http://localhost:8080/okhttp/PostReq");
  11. // post 文件请求(有参数请求时文件会失效,且未测试过)
  12. String res = RequestTool
  13. .post()
  14. .file(new File("lidaye.img"),"image/jpeg;charset=utf-8")
  15. .send("http://localhost:8080/okhttp/PostReq");
  16. // 自定义 post 请求(自定义RequestBody)
  17. String res = RequestTool.respString("http://localhost:8080/okhttp/PostReq", new RequestBody() {
  18. @Override
  19. public MediaType contentType() {
  20. // 请求内容类型
  21. return MediaType.parse("text/x-markdown; charset=utf-8");
  22. }
  23. @Override
  24. public void writeTo(BufferedSink sink) throws IOException {
  25. // 请求内容
  26. sink.writeUtf8("hello!");
  27. }
  28. });
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注