[关闭]
@linux1s1s 2016-11-18T11:06:13.000000Z 字数 11988 阅读 1779

Android 开源库 - OkHttp

AndroidRefine 2016-11


系列博文
Android 开源库 - OkHttp
Android 开源库 - Retrofit
Android 开源库 - Okio
Android 开源库 - Fresco

Demo

这里仅仅涉及如何使用OkHttp,并做了简单的工具封装,测试用例适用于okhttp:3.4.2

配置文件

  1. dependencies {
  2. compile fileTree(dir: 'libs', include: ['*.jar'])
  3. androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
  4. exclude group: 'com.android.support', module: 'support-annotations'
  5. })
  6. compile 'com.android.support:appcompat-v7:24.2.1'
  7. // OkHttp
  8. compile 'com.squareup.okhttp3:okhttp:3.4.2'
  9. // OkIo
  10. compile 'com.squareup.okio:okio:1.11.0'
  11. testCompile 'junit:junit:4.12'
  12. }

资源文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:id="@+id/activity_main"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. tools:context="okhttp.mutex.com.okhttpdemo.MainActivity">
  8. <RelativeLayout
  9. android:layout_width="match_parent"
  10. android:layout_height="wrap_content"
  11. android:paddingBottom="@dimen/activity_vertical_margin"
  12. android:paddingLeft="@dimen/activity_horizontal_margin"
  13. android:paddingRight="@dimen/activity_horizontal_margin"
  14. android:paddingTop="@dimen/activity_vertical_margin">
  15. <Button
  16. android:id="@+id/send_get"
  17. android:layout_width="200dp"
  18. android:layout_height="70dp"
  19. android:layout_centerHorizontal="true"
  20. android:onClick="sendGet"
  21. android:text="Get" />
  22. <Button
  23. android:id="@+id/send_get_header"
  24. android:layout_width="200dp"
  25. android:layout_height="70dp"
  26. android:layout_below="@id/send_get"
  27. android:layout_centerHorizontal="true"
  28. android:layout_marginTop="10dp"
  29. android:onClick="sendGetWithHeader"
  30. android:text="Get Header" />
  31. <Button
  32. android:id="@+id/send_get_async"
  33. android:layout_width="200dp"
  34. android:layout_height="70dp"
  35. android:layout_below="@id/send_get_header"
  36. android:layout_centerHorizontal="true"
  37. android:layout_marginTop="10dp"
  38. android:onClick="sendGetAsync"
  39. android:text="Get Async" />
  40. <Button
  41. android:id="@+id/send_get_header_async"
  42. android:layout_width="200dp"
  43. android:layout_height="70dp"
  44. android:layout_below="@id/send_get_async"
  45. android:layout_centerHorizontal="true"
  46. android:layout_marginTop="10dp"
  47. android:onClick="sendGetWithHeaderAsync"
  48. android:text="Get Async Header" />
  49. <Button
  50. android:id="@+id/send_post"
  51. android:layout_width="200dp"
  52. android:layout_height="70dp"
  53. android:layout_below="@id/send_get_header_async"
  54. android:layout_centerHorizontal="true"
  55. android:onClick="sendPost"
  56. android:text="Post" />
  57. <Button
  58. android:id="@+id/send_post_header"
  59. android:layout_width="200dp"
  60. android:layout_height="70dp"
  61. android:layout_below="@id/send_post"
  62. android:layout_centerHorizontal="true"
  63. android:layout_marginTop="10dp"
  64. android:onClick="sendPostWithHeader"
  65. android:text="Post Header" />
  66. <Button
  67. android:id="@+id/send_post_async"
  68. android:layout_width="200dp"
  69. android:layout_height="70dp"
  70. android:layout_below="@id/send_post_header"
  71. android:layout_centerHorizontal="true"
  72. android:layout_marginTop="10dp"
  73. android:onClick="sendPostAsync"
  74. android:text="post Async" />
  75. <Button
  76. android:id="@+id/send_post_header_async"
  77. android:layout_width="200dp"
  78. android:layout_height="70dp"
  79. android:layout_below="@id/send_post_async"
  80. android:layout_centerHorizontal="true"
  81. android:layout_marginTop="10dp"
  82. android:onClick="sendPostWithHeaderAsync"
  83. android:text="Post Async Header" />
  84. </RelativeLayout>
  85. </ScrollView>

测试源码

OkHttpUtil.java

这里将基本的OKHttp如何使用简单粗暴的封装为一个工具类,包含了get/post 分别带Header以及同步和异步请求8个简单的请求方法。

  1. import android.text.TextUtils;
  2. import java.io.IOException;
  3. import java.util.Map;
  4. import okhttp3.Callback;
  5. import okhttp3.FormBody;
  6. import okhttp3.MediaType;
  7. import okhttp3.OkHttpClient;
  8. import okhttp3.Request;
  9. import okhttp3.RequestBody;
  10. import okhttp3.Response;
  11. public class OkHttpUtil {
  12. private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
  13. private OkHttpUtil() {
  14. //Do nothing
  15. }
  16. private static OkHttpClient sOkHttpClient = new OkHttpClient();
  17. //********************Http Get Sync*************************//
  18. public static String okHttpGetSync(String url) {
  19. if (TextUtils.isEmpty(url))
  20. return null;
  21. Request request = new Request.Builder().url(url).build();
  22. try {
  23. Response response = sOkHttpClient.newCall(request).execute();
  24. if (response.isSuccessful()) {
  25. return response.body().string();
  26. }
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. return null;
  31. }
  32. //********************Http Get Async*************************//
  33. public static void okHttpGetAsync(String url, Callback callback) {
  34. if (TextUtils.isEmpty(url))
  35. return;
  36. Request request = new Request.Builder().url(url).build();
  37. sOkHttpClient.newCall(request).enqueue(callback);
  38. }
  39. //********************Http Get Sync With Headers*************************//
  40. public static String okHttpGetSync(String url, Map<String, String> headers) {
  41. if (TextUtils.isEmpty(url))
  42. return null;
  43. Request.Builder build = new Request.Builder().url(url);
  44. Request request = fillBuild(build, headers).build();
  45. try {
  46. Response response = sOkHttpClient.newCall(request).execute();
  47. if (response.isSuccessful()) {
  48. return response.body().string();
  49. }
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53. return null;
  54. }
  55. //********************Http Get Async With Headers*************************//
  56. public static void okHttpGetAsync(String url, Map<String, String> headers, Callback callback) {
  57. if (TextUtils.isEmpty(url))
  58. return;
  59. Request.Builder build = new Request.Builder().url(url);
  60. Request request = fillBuild(build, headers).build();
  61. sOkHttpClient.newCall(request).enqueue(callback);
  62. }
  63. //********************Http Post Sync*************************//
  64. public static String okHttpPostSyncWithForm(String url, Map<String, String> form) {
  65. return okHttpPostSyncWithHeaderForm(url, null, form);
  66. }
  67. //********************Http Post Sync With Header Form*************************//
  68. public static String okHttpPostSyncWithHeaderForm(String url, Map<String, String> headers, Map<String, String> form) {
  69. if (TextUtils.isEmpty(url))
  70. return null;
  71. FormBody body = null;
  72. if (form != null && !form.isEmpty()) {
  73. FormBody.Builder builder = new FormBody.Builder();
  74. for (Map.Entry<String, String> entry : form.entrySet()) {
  75. if (entry == null) continue;
  76. builder.add(entry.getKey(), entry.getValue());
  77. }
  78. body = builder.build();
  79. }
  80. Request.Builder requestBuilder = new Request.Builder().url(url);
  81. Request request;
  82. if (body != null) {
  83. request = fillBuild(requestBuilder, headers).post(body).build();
  84. } else {
  85. request = fillBuild(requestBuilder, headers).build();
  86. }
  87. try {
  88. Response response = sOkHttpClient.newCall(request).execute();
  89. if (response.isSuccessful()) {
  90. return response.body().string();
  91. }
  92. } catch (IOException e) {
  93. e.printStackTrace();
  94. }
  95. return null;
  96. }
  97. //********************Http Post Async With Form*************************//
  98. public static void okHttpPostAsyncWithForm(String url, Map<String, String> form, Callback callback) {
  99. okHttpPostAsyncWithHeaderForm(url, null, form, callback);
  100. }
  101. //********************Http Post Async With Headers Form*************************//
  102. public static void okHttpPostAsyncWithHeaderForm(String url, Map<String, String> headers, Map<String, String> form, Callback callback) {
  103. if (TextUtils.isEmpty(url))
  104. return;
  105. FormBody body = null;
  106. if (form != null && !form.isEmpty()) {
  107. FormBody.Builder builder = new FormBody.Builder();
  108. for (Map.Entry<String, String> entry : form.entrySet()) {
  109. if (entry == null) continue;
  110. builder.add(entry.getKey(), entry.getValue());
  111. }
  112. body = builder.build();
  113. }
  114. Request.Builder requestBuilder = new Request.Builder().url(url);
  115. Request request;
  116. if (body != null) {
  117. request = fillBuild(requestBuilder, headers).post(body).build();
  118. } else {
  119. request = fillBuild(requestBuilder, headers).build();
  120. }
  121. sOkHttpClient.newCall(request).enqueue(callback);
  122. }
  123. //********************Http Post Sync With Json*************************//
  124. public static String okHttpPostSyncWithJson(String url, String json) {
  125. return okHttpPostSyncWithHeaderJson(url, null, json);
  126. }
  127. private static String okHttpPostSyncWithHeaderJson(String url, Map<String, String> headers, String json) {
  128. if (TextUtils.isEmpty(url))
  129. return null;
  130. RequestBody body = RequestBody.create(JSON_TYPE, json);
  131. Request.Builder builder = new Request.Builder().url(url);
  132. Request request = fillBuild(builder, headers).post(body).build();
  133. try {
  134. Response res = sOkHttpClient.newCall(request).execute();
  135. if (res.isSuccessful()) {
  136. return res.body().string();
  137. }
  138. } catch (IOException e) {
  139. e.printStackTrace();
  140. }
  141. return null;
  142. }
  143. //********************Http Post Async With Json*************************//
  144. public static void okHttpPostAsyncWithJson(String url, String json, Callback callback) {
  145. okHttpPostAsyncWithHeaderJson(url, null, json, callback);
  146. }
  147. private static void okHttpPostAsyncWithHeaderJson(String url, Map<String, String> headers, String json, Callback callback) {
  148. if (TextUtils.isEmpty(url))
  149. return;
  150. RequestBody body = RequestBody.create(JSON_TYPE, json);
  151. Request.Builder builder = new Request.Builder().url(url);
  152. Request request = fillBuild(builder, headers).post(body).build();
  153. sOkHttpClient.newCall(request).enqueue(callback);
  154. }
  155. /**
  156. * 填充header
  157. *
  158. * @param input
  159. * @param headers
  160. * @return
  161. */
  162. private static Request.Builder fillBuild(Request.Builder input, Map<String, String> headers) {
  163. if (headers == null)
  164. return input;
  165. for (Map.Entry<String, String> entry : headers.entrySet()) {
  166. String key = entry.getKey();
  167. String value = entry.getValue();
  168. input.header(key, value);
  169. }
  170. return input;
  171. }
  172. }
MainActivity.java

主界面TestCase

  1. public class MainActivity extends AppCompatActivity {
  2. private static final String URL = "test api";
  3. @Override
  4. protected void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.activity_main);
  7. }
  8. /**
  9. * get方式请求API,同步
  10. *
  11. * @param view
  12. */
  13. public void sendGet(final View view) {
  14. new Thread() {
  15. @Override
  16. public void run() {
  17. final String result = OkHttpUtil.okHttpGetSync(URL);
  18. runOnUiThread(new Runnable() {
  19. @Override
  20. public void run() {
  21. Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
  22. }
  23. });
  24. }
  25. }.start();
  26. }
  27. /**
  28. * get方式请求API,异步
  29. *
  30. * @param view
  31. */
  32. public void sendGetAsync(final View view) {
  33. final Callback callback = obtainCommonCallback();
  34. new Thread() {
  35. @Override
  36. public void run() {
  37. OkHttpUtil.okHttpGetAsync(URL, callback);
  38. }
  39. }.start();
  40. }
  41. /**
  42. * get方式请求API,同步,添加Header
  43. *
  44. * @param view
  45. */
  46. public void sendGetWithHeader(final View view) {
  47. new Thread() {
  48. @Override
  49. public void run() {
  50. final String result = OkHttpUtil.okHttpGetSync(URL, obtainCommonHeader());
  51. runOnUiThread(new Runnable() {
  52. @Override
  53. public void run() {
  54. Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
  55. }
  56. });
  57. }
  58. }.start();
  59. }
  60. /**
  61. * get方式请求API,异步,添加Header
  62. *
  63. * @param view
  64. */
  65. public void sendGetWithHeaderAsync(final View view) {
  66. final Callback callback = obtainCommonCallback();
  67. new Thread() {
  68. @Override
  69. public void run() {
  70. OkHttpUtil.okHttpGetAsync(URL, obtainCommonHeader(), callback);
  71. }
  72. }.start();
  73. }
  74. public void sendPost(final View view) {
  75. new Thread() {
  76. @Override
  77. public void run() {
  78. final String result = OkHttpUtil.okHttpPostSyncWithForm(URL, obtainCommonForm());
  79. runOnUiThread(new Runnable() {
  80. @Override
  81. public void run() {
  82. Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
  83. }
  84. });
  85. }
  86. }.start();
  87. }
  88. public void sendPostWithHeader(final View view) {
  89. new Thread() {
  90. @Override
  91. public void run() {
  92. final String result = OkHttpUtil.okHttpPostSyncWithHeaderForm(URL, obtainCommonHeader(), obtainCommonForm());
  93. runOnUiThread(new Runnable() {
  94. @Override
  95. public void run() {
  96. Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
  97. }
  98. });
  99. }
  100. }.start();
  101. }
  102. public void sendPostAsync(final View view) {
  103. new Thread() {
  104. @Override
  105. public void run() {
  106. OkHttpUtil.okHttpPostAsyncWithForm(URL, obtainCommonForm(), obtainCommonCallback());
  107. }
  108. }.start();
  109. }
  110. public void sendPostWithHeaderAsync(final View view) {
  111. new Thread() {
  112. @Override
  113. public void run() {
  114. OkHttpUtil.okHttpPostAsyncWithHeaderForm(URL, obtainCommonHeader(), obtainCommonForm(), obtainCommonCallback());
  115. }
  116. }.start();
  117. }
  118. private Callback obtainCommonCallback() {
  119. return new Callback() {
  120. @Override
  121. public void onFailure(Call call, final IOException e) {
  122. runOnUiThread(new Runnable() {
  123. @Override
  124. public void run() {
  125. Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
  126. }
  127. });
  128. }
  129. @Override
  130. public void onResponse(Call call, final Response response) throws IOException {
  131. if (response.isSuccessful()) {
  132. final String rs = response.body().string();
  133. runOnUiThread(new Runnable() {
  134. @Override
  135. public void run() {
  136. Toast.makeText(MainActivity.this, rs, Toast.LENGTH_SHORT).show();
  137. }
  138. });
  139. }
  140. }
  141. };
  142. }
  143. private Map<String, String> obtainCommonHeader() {
  144. Map<String, String> headers = new HashMap<>();
  145. headers.put("Atest", "Aheader");
  146. headers.put("Btest", "Bheader");
  147. headers.put("Ctest", "Cheader");
  148. headers.put("Dtest", "Dheader");
  149. return headers;
  150. }
  151. private Map<String, String> obtainCommonForm() {
  152. Map<String, String> from = new HashMap<>();
  153. from.put("AFormKey", "FormValueA");
  154. from.put("BFormKey", "FormValueB");
  155. from.put("BFormKey", "FormValueC");
  156. from.put("BFormKey", "FormValueD");
  157. return from;
  158. }
  159. }

验证结果

参考文章:
OkHttp GitHub Doc
Retrofit GitHub DocR Doc
Fresco GitHub Doc
Okio GitHub Video

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注