OkHttpRequest.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package com.zhy.http.okhttp.request;
  2. import com.zhy.http.okhttp.callback.Callback;
  3. import com.zhy.http.okhttp.utils.Exceptions;
  4. import java.util.Map;
  5. import okhttp3.Headers;
  6. import okhttp3.Request;
  7. import okhttp3.RequestBody;
  8. /**
  9. * Created by zhy on 15/11/6.
  10. */
  11. public abstract class OkHttpRequest
  12. {
  13. protected String url;
  14. protected Object tag;
  15. protected Map<String, String> params;
  16. protected Map<String, String> headers;
  17. protected int id;
  18. protected Request.Builder builder = new Request.Builder();
  19. protected OkHttpRequest(String url, Object tag,
  20. Map<String, String> params, Map<String, String> headers,int id)
  21. {
  22. this.url = url;
  23. this.tag = tag;
  24. this.params = params;
  25. this.headers = headers;
  26. this.id = id ;
  27. if (url == null)
  28. {
  29. Exceptions.illegalArgument("url can not be null.");
  30. }
  31. initBuilder();
  32. }
  33. /**
  34. * 初始化一些基本参数 url , tag , headers
  35. */
  36. private void initBuilder()
  37. {
  38. builder.url(url).tag(tag);
  39. appendHeaders();
  40. }
  41. protected abstract RequestBody buildRequestBody();
  42. protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
  43. {
  44. return requestBody;
  45. }
  46. protected abstract Request buildRequest(RequestBody requestBody);
  47. public RequestCall build()
  48. {
  49. return new RequestCall(this);
  50. }
  51. public Request generateRequest(Callback callback)
  52. {
  53. RequestBody requestBody = buildRequestBody();
  54. RequestBody wrappedRequestBody = wrapRequestBody(requestBody, callback);
  55. Request request = buildRequest(wrappedRequestBody);
  56. return request;
  57. }
  58. protected void appendHeaders()
  59. {
  60. Headers.Builder headerBuilder = new Headers.Builder();
  61. if (headers == null || headers.isEmpty()) return;
  62. for (String key : headers.keySet())
  63. {
  64. headerBuilder.add(key, headers.get(key));
  65. }
  66. builder.headers(headerBuilder.build());
  67. }
  68. public int getId()
  69. {
  70. return id ;
  71. }
  72. }