@linux1s1s
2016-11-18T11:06:13.000000Z
字数 11988
阅读 1797
AndroidRefine
2016-11
系列博文
Android 开源库 - OkHttp
Android 开源库 - Retrofit
Android 开源库 - Okio
Android 开源库 - Fresco
这里仅仅涉及如何使用OkHttp,并做了简单的工具封装,测试用例适用于okhttp:3.4.2
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
// OkHttp
compile 'com.squareup.okhttp3:okhttp:3.4.2'
// OkIo
compile 'com.squareup.okio:okio:1.11.0'
testCompile 'junit:junit:4.12'
}
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="okhttp.mutex.com.okhttpdemo.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<Button
android:id="@+id/send_get"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:onClick="sendGet"
android:text="Get" />
<Button
android:id="@+id/send_get_header"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_below="@id/send_get"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:onClick="sendGetWithHeader"
android:text="Get Header" />
<Button
android:id="@+id/send_get_async"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_below="@id/send_get_header"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:onClick="sendGetAsync"
android:text="Get Async" />
<Button
android:id="@+id/send_get_header_async"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_below="@id/send_get_async"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:onClick="sendGetWithHeaderAsync"
android:text="Get Async Header" />
<Button
android:id="@+id/send_post"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_below="@id/send_get_header_async"
android:layout_centerHorizontal="true"
android:onClick="sendPost"
android:text="Post" />
<Button
android:id="@+id/send_post_header"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_below="@id/send_post"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:onClick="sendPostWithHeader"
android:text="Post Header" />
<Button
android:id="@+id/send_post_async"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_below="@id/send_post_header"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:onClick="sendPostAsync"
android:text="post Async" />
<Button
android:id="@+id/send_post_header_async"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_below="@id/send_post_async"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:onClick="sendPostWithHeaderAsync"
android:text="Post Async Header" />
</RelativeLayout>
</ScrollView>
这里将基本的OKHttp如何使用简单粗暴的封装为一个工具类,包含了get/post 分别带Header以及同步和异步请求8个简单的请求方法。
import android.text.TextUtils;
import java.io.IOException;
import java.util.Map;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class OkHttpUtil {
private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
private OkHttpUtil() {
//Do nothing
}
private static OkHttpClient sOkHttpClient = new OkHttpClient();
//********************Http Get Sync*************************//
public static String okHttpGetSync(String url) {
if (TextUtils.isEmpty(url))
return null;
Request request = new Request.Builder().url(url).build();
try {
Response response = sOkHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//********************Http Get Async*************************//
public static void okHttpGetAsync(String url, Callback callback) {
if (TextUtils.isEmpty(url))
return;
Request request = new Request.Builder().url(url).build();
sOkHttpClient.newCall(request).enqueue(callback);
}
//********************Http Get Sync With Headers*************************//
public static String okHttpGetSync(String url, Map<String, String> headers) {
if (TextUtils.isEmpty(url))
return null;
Request.Builder build = new Request.Builder().url(url);
Request request = fillBuild(build, headers).build();
try {
Response response = sOkHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//********************Http Get Async With Headers*************************//
public static void okHttpGetAsync(String url, Map<String, String> headers, Callback callback) {
if (TextUtils.isEmpty(url))
return;
Request.Builder build = new Request.Builder().url(url);
Request request = fillBuild(build, headers).build();
sOkHttpClient.newCall(request).enqueue(callback);
}
//********************Http Post Sync*************************//
public static String okHttpPostSyncWithForm(String url, Map<String, String> form) {
return okHttpPostSyncWithHeaderForm(url, null, form);
}
//********************Http Post Sync With Header Form*************************//
public static String okHttpPostSyncWithHeaderForm(String url, Map<String, String> headers, Map<String, String> form) {
if (TextUtils.isEmpty(url))
return null;
FormBody body = null;
if (form != null && !form.isEmpty()) {
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry<String, String> entry : form.entrySet()) {
if (entry == null) continue;
builder.add(entry.getKey(), entry.getValue());
}
body = builder.build();
}
Request.Builder requestBuilder = new Request.Builder().url(url);
Request request;
if (body != null) {
request = fillBuild(requestBuilder, headers).post(body).build();
} else {
request = fillBuild(requestBuilder, headers).build();
}
try {
Response response = sOkHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//********************Http Post Async With Form*************************//
public static void okHttpPostAsyncWithForm(String url, Map<String, String> form, Callback callback) {
okHttpPostAsyncWithHeaderForm(url, null, form, callback);
}
//********************Http Post Async With Headers Form*************************//
public static void okHttpPostAsyncWithHeaderForm(String url, Map<String, String> headers, Map<String, String> form, Callback callback) {
if (TextUtils.isEmpty(url))
return;
FormBody body = null;
if (form != null && !form.isEmpty()) {
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry<String, String> entry : form.entrySet()) {
if (entry == null) continue;
builder.add(entry.getKey(), entry.getValue());
}
body = builder.build();
}
Request.Builder requestBuilder = new Request.Builder().url(url);
Request request;
if (body != null) {
request = fillBuild(requestBuilder, headers).post(body).build();
} else {
request = fillBuild(requestBuilder, headers).build();
}
sOkHttpClient.newCall(request).enqueue(callback);
}
//********************Http Post Sync With Json*************************//
public static String okHttpPostSyncWithJson(String url, String json) {
return okHttpPostSyncWithHeaderJson(url, null, json);
}
private static String okHttpPostSyncWithHeaderJson(String url, Map<String, String> headers, String json) {
if (TextUtils.isEmpty(url))
return null;
RequestBody body = RequestBody.create(JSON_TYPE, json);
Request.Builder builder = new Request.Builder().url(url);
Request request = fillBuild(builder, headers).post(body).build();
try {
Response res = sOkHttpClient.newCall(request).execute();
if (res.isSuccessful()) {
return res.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//********************Http Post Async With Json*************************//
public static void okHttpPostAsyncWithJson(String url, String json, Callback callback) {
okHttpPostAsyncWithHeaderJson(url, null, json, callback);
}
private static void okHttpPostAsyncWithHeaderJson(String url, Map<String, String> headers, String json, Callback callback) {
if (TextUtils.isEmpty(url))
return;
RequestBody body = RequestBody.create(JSON_TYPE, json);
Request.Builder builder = new Request.Builder().url(url);
Request request = fillBuild(builder, headers).post(body).build();
sOkHttpClient.newCall(request).enqueue(callback);
}
/**
* 填充header
*
* @param input
* @param headers
* @return
*/
private static Request.Builder fillBuild(Request.Builder input, Map<String, String> headers) {
if (headers == null)
return input;
for (Map.Entry<String, String> entry : headers.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
input.header(key, value);
}
return input;
}
}
主界面TestCase
public class MainActivity extends AppCompatActivity {
private static final String URL = "test api";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* get方式请求API,同步
*
* @param view
*/
public void sendGet(final View view) {
new Thread() {
@Override
public void run() {
final String result = OkHttpUtil.okHttpGetSync(URL);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}
}.start();
}
/**
* get方式请求API,异步
*
* @param view
*/
public void sendGetAsync(final View view) {
final Callback callback = obtainCommonCallback();
new Thread() {
@Override
public void run() {
OkHttpUtil.okHttpGetAsync(URL, callback);
}
}.start();
}
/**
* get方式请求API,同步,添加Header
*
* @param view
*/
public void sendGetWithHeader(final View view) {
new Thread() {
@Override
public void run() {
final String result = OkHttpUtil.okHttpGetSync(URL, obtainCommonHeader());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}
}.start();
}
/**
* get方式请求API,异步,添加Header
*
* @param view
*/
public void sendGetWithHeaderAsync(final View view) {
final Callback callback = obtainCommonCallback();
new Thread() {
@Override
public void run() {
OkHttpUtil.okHttpGetAsync(URL, obtainCommonHeader(), callback);
}
}.start();
}
public void sendPost(final View view) {
new Thread() {
@Override
public void run() {
final String result = OkHttpUtil.okHttpPostSyncWithForm(URL, obtainCommonForm());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}
}.start();
}
public void sendPostWithHeader(final View view) {
new Thread() {
@Override
public void run() {
final String result = OkHttpUtil.okHttpPostSyncWithHeaderForm(URL, obtainCommonHeader(), obtainCommonForm());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}
}.start();
}
public void sendPostAsync(final View view) {
new Thread() {
@Override
public void run() {
OkHttpUtil.okHttpPostAsyncWithForm(URL, obtainCommonForm(), obtainCommonCallback());
}
}.start();
}
public void sendPostWithHeaderAsync(final View view) {
new Thread() {
@Override
public void run() {
OkHttpUtil.okHttpPostAsyncWithHeaderForm(URL, obtainCommonHeader(), obtainCommonForm(), obtainCommonCallback());
}
}.start();
}
private Callback obtainCommonCallback() {
return new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (response.isSuccessful()) {
final String rs = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, rs, Toast.LENGTH_SHORT).show();
}
});
}
}
};
}
private Map<String, String> obtainCommonHeader() {
Map<String, String> headers = new HashMap<>();
headers.put("Atest", "Aheader");
headers.put("Btest", "Bheader");
headers.put("Ctest", "Cheader");
headers.put("Dtest", "Dheader");
return headers;
}
private Map<String, String> obtainCommonForm() {
Map<String, String> from = new HashMap<>();
from.put("AFormKey", "FormValueA");
from.put("BFormKey", "FormValueB");
from.put("BFormKey", "FormValueC");
from.put("BFormKey", "FormValueD");
return from;
}
}
运行以后的主界面
Charles抓包
参考文章:
OkHttp GitHub Doc
Retrofit GitHub DocR Doc
Fresco GitHub Doc
Okio GitHub Video