本文主要是介绍OkHttp学习(1)--同步和异步(get、post键值对、post带map、请求头体封装json),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
之前学习过Volley的种种用法,点击如下链接可以参考
如果想对Volley有所了解,可以看我这5篇关于Volley的实践代码
今天来学习下OkHttp的学习,这篇博客主要是来了解OkHttp同步和异步—(get、post键值对、post带map、请求头体封装json)
下一篇去了解文件上传、图片下载
为了快速使用,没有去研究源码了,但是看过Volley的源码,我感觉本质上也是想通的,就直接通过demo的跑通方式来了解把
我通过http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly这个进行测试
返回的Json格式如下:
{"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001}
首先看主页布局
先来了解下关于同步请求的方法
1、先看第一种,同步get请求
new Thread() {@Overridepublic void run() {try {Response response = OkHttpManger.getInstance().getSync("http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly");if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity", "getSync:" + responseStr);}} catch (IOException e) {e.printStackTrace();}}}.start();
我们在第一个方法里面,看看OkHttpManger做了什么操作?
OkHttpManger.getInstance().getSync(“http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly“);
private Handler okHttpHandler;private OkHttpClient mOkHttpClient;private OkHttpManger(){this.mOkHttpClient = SaflyApplication.getInstance().getUnsafeOkHttpClient();this.okHttpHandler = new Handler(Looper.getMainLooper());}public static final OkHttpManger getInstance(){return SingleFactory.manger;}private static final class SingleFactory{private static final OkHttpManger manger = new OkHttpManger();}
我们本篇博客,需要测试在请求体传json的例子,由于公司是https的,我就直接信任所有的证书了,
在getInstance中就是一个单利模式,然后封装了一个handler用于主线程更新使用
getUnsafeOkHttpClient我是网上找的代码–我没有跟公司的进行认证请求(这个不是这篇的学习了解重点)
public static OkHttpClient getUnsafeOkHttpClient() {try {final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return new java.security.cert.X509Certificate[]{};}}};final SSLContext sslContext = SSLContext.getInstance("SSL");sslContext.init(null, trustAllCerts, new java.security.SecureRandom());final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();OkHttpClient.Builder builder = new OkHttpClient.Builder();builder.sslSocketFactory(sslSocketFactory);builder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});OkHttpClient okHttpClient = builder.connectTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).build();return okHttpClient;} catch (Exception e) {throw new RuntimeException(e);}}
OkHttpClient okHttpClient = builder.connectTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).build();这里就是okHttpClient的操作
在getSync方法中,就是调用了ok的方法,构造请求Request ,Call 然后直接执行即可,返回一个Response
public Response getSync(final String url) throws IOException {final Request request = new Request.Builder().url(url).build();final Call call = mOkHttpClient.newCall(request);return call.execute();}
然后,进行更新即可
if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity", "getSync:" + responseStr);}
2、先看第1种,同步post请求,添加params方式
final OkHttpManger.Param param1 = new OkHttpManger.Param("phone","13429667914");final OkHttpManger.Param param2 = new OkHttpManger.Param("key","safly");new Thread() {@Overridepublic void run() {try {Response response = OkHttpManger.getInstance().postSync("http://apis.juhe.cn/mobile/get",param1,param2);if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity","postSyncByParams1:"+responseStr);}} catch (IOException e) {e.printStackTrace();}}}.start();
final Request request = buildPostRequst(url, params);final Call call = mOkHttpClient.newCall(request);return call.execute();}
这里就看看buildPostRequst方法
private Request buildPostRequst(String url, Param... params){if(params == null){params = new Param[0];}FormBody.Builder builder = new FormBody.Builder();for(Param param:params){builder.add(param.key,param.value);}return new Request.Builder().url(url).post(builder.build()).build();}
然后依然在主界面进行更新即可
3、先看第3种,同步post请求,添加map集合方式
final HashMap<String,String> maps = new HashMap<>();maps.put("phone","13429667914");maps.put("key","safly");new Thread() {@Overridepublic void run() {try {Response response = OkHttpManger.getInstance().postSync("http://apis.juhe.cn/mobile/get",maps);if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity","postSyncByParams2:"+responseStr);}} catch (IOException e) {e.printStackTrace();}}}.start();
public Response postSync(String url, Map<String,String> params) throws IOException {final Request request = buildPostRequst(url, params);final Call call = mOkHttpClient.newCall(request);return call.execute();}
private Request buildPostRequst(String url, Map<String,String> params){Request request = null;if(params == null){params = new HashMap<>();}if(params != null){Set<Map.Entry<String,String>> entries = params.entrySet();FormBody.Builder builder = new FormBody.Builder();for(Map.Entry<String,String> entry:entries){builder.add(entry.getKey(),entry.getValue());}request = new Request.Builder().url(url).post(builder.build()).build();}return request;}
代码简单,然后依然是在主界面进行其他操作
4、先看第4种,同步post请求,添加Json请求体请求方式
try {Json = createJson();Log.i("MainActivity","postSyncByParams2 Json:"+Json);} catch (JSONException e) {e.printStackTrace();}new Thread() {@Overridepublic void run() {try {Response response = OkHttpManger.getInstance().postSyncJson("https://www.imlianxi.com:xxxx/AppFeedback", Json);if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity","postSyncByParams2:"+responseStr);}else{Log.i("MainActivity","postSyncByParams2 error");}} catch (IOException e) {e.printStackTrace();}}}.start();
这是我公司的项目ulr,我用xxxx号码替代了,不方便暴露,嘿嘿嘿
我这里构造json直接用的JSONObject
private String createJson() throws JSONException {JSONObject jsonObject = new JSONObject();JSONObject body = new JSONObject();body.put("phoneimei", "353490061934846");body.put("context", "反馈");JSONObject head = new JSONObject();head.put("app_type", "3");head.put("os_type", "android");head.put("osversion", "5.1.1");head.put("appversion", "1.0");head.put("devicefactory", "LGE");head.put("devicemodel", "AOSP on HammerHead");JSONObject Request = new JSONObject();Request.put("body", body);Request.put("head", head);jsonObject.put("Request", Request);return jsonObject.toString();}
public Response postSyncJson(String url, String json) throws IOException {final RequestBody requestBody = RequestBody.create(JSON_TYPE, json);final Request request = new Request.Builder().url(url).post(requestBody).build();return mOkHttpClient.newCall(request).execute();}
然后在主界面做其他操作即可
以上就是同步请求,我们接下来看看异步操作请求
5、先看第5种,异步get请求
try {OkHttpManger.getInstance().getAsync("http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly", new OKHttpUICallback.ResultCallback<Result>() {@Overridepublic void onSuccess(Result result) {Log.i("MainActivity","result:"+result.toString());}@Overridepublic void onError(Call call, IOException e) {}});} catch (IOException e) {e.printStackTrace();}
用这个进行测试http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly
返回的格式
{"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001}
封装个对象把如下
package utils;/*** {"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001}*/
public class Result {private String resultcode;private String reason;private String result;private int error_code;public Result(String resultcode, String reason, String result, int error_code) {this.resultcode = resultcode;this.reason = reason;this.result = result;this.error_code = error_code;}public Result() {}@Overridepublic String toString() {return "Result{" +"resultcode='" + resultcode + '\'' +", reason='" + reason + '\'' +", result='" + result + '\'' +", error_code=" + error_code +'}';}public String getResultcode() {return resultcode;}public String getReason() {return reason;}public String getResult() {return result;}public int getError_code() {return error_code;}public void setResultcode(String resultcode) {this.resultcode = resultcode;}public void setReason(String reason) {this.reason = reason;}public void setResult(String result) {this.result = result;}public void setError_code(int error_code) {this.error_code = error_code;}
}
看看方法把:
try {OkHttpManger.getInstance().getAsync("http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly", new OKHttpUICallback.ResultCallback<Result>() {@Overridepublic void onSuccess(Result result) {Log.i("MainActivity","result:"+result.toString());}@Overridepublic void onError(Call call, IOException e) {}});} catch (IOException e) {e.printStackTrace();}
public void getAsync(final String url, final OKHttpUICallback.ResultCallback callback)throws IOException {final Request request = new Request.Builder().url(url).build();final Call call = mOkHttpClient.newCall(request);deliveryResult(call, callback);}
在楼上的代码,带一个回调 OKHttpUICallback.ResultCallback callback
然后请求完毕后,在次进行接口回调,去主界面进行相应操作
private void deliveryResult(final Call call, final OKHttpUICallback.ResultCallback callback){call.enqueue(new Callback() {@Overridepublic void onFailure(final Call call, final IOException e) {okHttpHandler.post(new Runnable() {@Overridepublic void run() {if (callback != null) {callback.onError(call, e);}}});}@Overridepublic void onResponse(Call call, Response response) throws IOException {if(callback != null){final Object object = JSON.parseObject(response.body().string(), callback.mType);okHttpHandler.post(new Runnable() {@Overridepublic void run() {callback.onSuccess(object);}});}}});}
我们看看OKHttpUICallback.ResultCallback callback
public static abstract class ResultCallback<T>{public Type mType;public ResultCallback(){mType = getSuperclassTypeParameter(getClass());}private static Type getSuperclassTypeParameter(Class<?> subclass){Type superclass = subclass.getGenericSuperclass();if(superclass instanceof Class){throw new RuntimeException("Miss type parameter");}ParameterizedType parameterizedType = (ParameterizedType)superclass;return parameterizedType.getActualTypeArguments()[0];}public abstract void onSuccess(T result);public abstract void onError(Call call, IOException e);}
我这里是用了阿里的封装类jar
if(callback != null){final Object object = JSON.parseObject(response.body().string(), callback.mType);okHttpHandler.post(new Runnable() {@Overridepublic void run() {callback.onSuccess(object);}});}
封装完毕,post到主线程做其他操作即可
67、第6、7种省略–代码大同小异,下面代码附上
8、看第8种,异步post传json请求
这个我们用另外一个
try {Json = createJson();Log.i("MainActivity","postSyncByParams2 Json:"+Json);} catch (JSONException e) {e.printStackTrace();}try {OkHttpManger.getInstance().postAsyncJsonn("https://www.imlianxi.com:xxxx/AppFeedback", Json, new OkHttpManger.MyCallback() {@Overridepublic void onSuccess(String result) {Log.i("MainActivity","result----"+result);}@Overridepublic void onFailture() {}});} catch (IOException e) {e.printStackTrace();}
interface MyCallback{void onSuccess(String result);void onFailture();}public void postAsyncJsonn(String url, String json, MyCallback mCallback) throws IOException {final RequestBody requestBody = RequestBody.create(JSON_TYPE, json);final Request request = new Request.Builder().url(url).post(requestBody).build();deliveryResult(mOkHttpClient.newCall(request),mCallback);}private void deliveryResult(final Call call, final MyCallback mCallback){call.enqueue(new Callback() {@Overridepublic void onFailure(final Call call, final IOException e) {okHttpHandler.post(new Runnable() {@Overridepublic void run() {if (mCallback !=null){mCallback.onFailture();}}});}@Overridepublic void onResponse(Call call, final Response response) throws IOException {final String responseStr = response.body().string();okHttpHandler.post(new Runnable() {@Overridepublic void run() {if (mCallback != null) {mCallback.onSuccess(responseStr);}}});}});}
定义了一个接口,不过没有封装对象类,收到相应后,在通过一个接口回调即可
———-以下是代码———————–以下是代码—————以下是代码————————–
MainActivity
package com.example.administrator.myapplication;import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;import org.json.JSONException;
import org.json.JSONObject;import java.io.IOException;
import java.util.HashMap;import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import utils.Result;/*** http://www.imooc.com/api/teacher?type=4&num=30*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {private String responseStr;private Handler mHandler;TextView textView;Button getSync,postSyncByParams1,postSyncByParams2,postSyncJson;Button getAsync,postAsyncParams,postAsyncByParams2,postAsyncJson;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = (TextView) findViewById(R.id.textView);//同步getSync = (Button) findViewById(R.id.getSync);postSyncByParams1 = (Button) findViewById(R.id.postSyncByParams1);postSyncByParams2 = (Button) findViewById(R.id.postSyncByParams2);postSyncJson = (Button) findViewById(R.id.postSyncJson);//异步getAsync = (Button) findViewById(R.id.getAsync);postAsyncParams = (Button) findViewById(R.id.postAsyncParams);postAsyncByParams2 = (Button) findViewById(R.id.postAsyncByParams2);postAsyncJson = (Button) findViewById(R.id.postAsyncJson);getSync.setOnClickListener(this);postSyncByParams1.setOnClickListener(this);postSyncByParams2.setOnClickListener(this);postSyncJson.setOnClickListener(this);getAsync.setOnClickListener(this);postAsyncParams.setOnClickListener(this);postAsyncByParams2.setOnClickListener(this);postAsyncJson.setOnClickListener(this);mHandler = new Handler(){public void handleMessage(android.os.Message msg) {if (msg.what == 1) {textView.setText(responseStr);}};};}@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.getSync:new Thread() {@Overridepublic void run() {try {Response response = OkHttpManger.getInstance().getSync("http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly");if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity", "getSync:" + responseStr);}} catch (IOException e) {e.printStackTrace();}}}.start();break;case R.id.postSyncByParams1:final OkHttpManger.Param param1 = new OkHttpManger.Param("phone","13429667914");final OkHttpManger.Param param2 = new OkHttpManger.Param("key","safly");new Thread() {@Overridepublic void run() {try {Response response = OkHttpManger.getInstance().postSync("http://apis.juhe.cn/mobile/get",param1,param2);if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity","postSyncByParams1:"+responseStr);}} catch (IOException e) {e.printStackTrace();}}}.start();break;case R.id.postSyncByParams2:final HashMap<String,String> maps = new HashMap<>();maps.put("phone","13429667914");maps.put("key","safly");new Thread() {@Overridepublic void run() {try {Response response = OkHttpManger.getInstance().postSync("http://apis.juhe.cn/mobile/get",maps);if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity","postSyncByParams2:"+responseStr);}} catch (IOException e) {e.printStackTrace();}}}.start();break;case R.id.postSyncJson:try {Json = createJson();Log.i("MainActivity","postSyncByParams2 Json:"+Json);} catch (JSONException e) {e.printStackTrace();}new Thread() {@Overridepublic void run() {try {Response response = OkHttpManger.getInstance().postSyncJson("https://www.imlianxi.com:7773/AppFeedback", Json);if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity","postSyncByParams2:"+responseStr);}else{Log.i("MainActivity","postSyncByParams2 error");}} catch (IOException e) {e.printStackTrace();}}}.start();break;//{"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001}case R.id.getAsync:try {OkHttpManger.getInstance().getAsync("http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly", new OKHttpUICallback.ResultCallback<Result>() {@Overridepublic void onSuccess(Result result) {Log.i("MainActivity","result:"+result.toString());}@Overridepublic void onError(Call call, IOException e) {}});} catch (IOException e) {e.printStackTrace();}break;case R.id.postAsyncParams:final OkHttpManger.Param param11 = new OkHttpManger.Param("phone","13429667914");final OkHttpManger.Param param22 = new OkHttpManger.Param("key","safly");try {OkHttpManger.getInstance().postAsync("http://apis.juhe.cn/mobile/get", new OKHttpUICallback.ResultCallback<Result>() {@Overridepublic void onSuccess(Result result) {Log.i("MainActivity", "result:" + result.toString());}@Overridepublic void onError(Call call, IOException e) {}},param11,param22);} catch (IOException e) {e.printStackTrace();}break;case R.id.postAsyncByParams2:final HashMap<String,String> mapss = new HashMap<>();mapss.put("phone","13429667914");mapss.put("key","safly");try {OkHttpManger.getInstance().postAsync("http://apis.juhe.cn/mobile/get", new OKHttpUICallback.ResultCallback<Result>() {@Overridepublic void onSuccess(Result result) {Log.i("MainActivity", "result:" + result.toString());}@Overridepublic void onError(Call call, IOException e) {}},mapss);} catch (IOException e) {e.printStackTrace();}break;/*** {"Response":{"head":{"statuscode":"113166","statusmsg":"Important parameter error"}}}*/case R.id.postAsyncJson:try {Json = createJson();Log.i("MainActivity","postSyncByParams2 Json:"+Json);} catch (JSONException e) {e.printStackTrace();}try {OkHttpManger.getInstance().postAsyncJsonn("https://www.imlianxi.com:7773/AppFeedback", Json, new OkHttpManger.MyCallback() {@Overridepublic void onSuccess(String result) {Log.i("MainActivity","result----"+result);}@Overridepublic void onFailture() {}});} catch (IOException e) {e.printStackTrace();}break;case R.id.uploadAsync1:case R.id.uploadAsync2:case R.id.uploadSync1:case R.id.uploadSync2:Toast.makeText(MainActivity.this, "暂时无接口测试后续补充。。。", Toast.LENGTH_SHORT).show();break;case R.id.downloadAsync:break;}}String Json = null;private String createJson() throws JSONException {JSONObject jsonObject = new JSONObject();JSONObject body = new JSONObject();body.put("phoneimei", "353490061934846");body.put("context", "反馈");JSONObject head = new JSONObject();head.put("app_type", "3");head.put("os_type", "android");head.put("osversion", "5.1.1");head.put("appversion", "1.0");head.put("devicefactory", "LGE");head.put("devicemodel", "AOSP on HammerHead");JSONObject Request = new JSONObject();Request.put("body", body);Request.put("head", head);jsonObject.put("Request", Request);return jsonObject.toString();}
}
SaflyApplication
package com.example.administrator.myapplication;import android.app.Application;import java.util.concurrent.TimeUnit;import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;import okhttp3.OkHttpClient;public class SaflyApplication extends Application {private static SaflyApplication instance;@Overridepublic void onCreate() {super.onCreate();this.instance = this;}public static SaflyApplication getInstance() {return instance;}public static OkHttpClient getUnsafeOkHttpClient() {try {final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return new java.security.cert.X509Certificate[]{};}}};final SSLContext sslContext = SSLContext.getInstance("SSL");sslContext.init(null, trustAllCerts, new java.security.SecureRandom());final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();OkHttpClient.Builder builder = new OkHttpClient.Builder();builder.sslSocketFactory(sslSocketFactory);builder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});OkHttpClient okHttpClient = builder.connectTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).build();return okHttpClient;} catch (Exception e) {throw new RuntimeException(e);}}
}
OkHttpManger
package com.example.administrator.myapplication;import android.os.Handler;
import android.os.Looper;
import android.util.Log;import com.alibaba.fastjson.JSON;import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;/*** OkHttp 工具类,* get的同步异步请求* post的json字符串同步异步上传* post的键值对同步异步上传* post文件异步上传,回调结果以及进度* 异步下载文件,回调结果以及进度** Created by Seeker on 2016/6/24.*/
public final class OkHttpManger {private static final String TAG = "OkHttpManger";private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");private Handler okHttpHandler;private OkHttpClient mOkHttpClient;private OkHttpManger(){this.mOkHttpClient = SaflyApplication.getInstance().getUnsafeOkHttpClient();this.okHttpHandler = new Handler(Looper.getMainLooper());}public static final OkHttpManger getInstance(){return SingleFactory.manger;}private static final class SingleFactory{private static final OkHttpManger manger = new OkHttpManger();}/*** 同步get请求** @param url 地址* @return Response 返回数据*/public Response getSync(final String url) throws IOException {final Request request = new Request.Builder().url(url).build();final Call call = mOkHttpClient.newCall(request);return call.execute();}/*** 同步post请求,键值对** @param url 地址* @param params 参数* Request.Builder().url(url).post(builder.build()).build();*/public Response postSync(String url, Param... params) throws IOException {final Request request = buildPostRequst(url, params);final Call call = mOkHttpClient.newCall(request);return call.execute();}/*** 同步post请求,键值对** @param url 地址* @param params 参数*/public Response postSync(String url, Map<String,String> params) throws IOException {final Request request = buildPostRequst(url, params);final Call call = mOkHttpClient.newCall(request);return call.execute();}/*** post同步请求,提交Json数据** @param url 地址* @param json json格式的字符串* @return Response*/public Response postSyncJson(String url, String json) throws IOException {final RequestBody requestBody = RequestBody.create(JSON_TYPE, json);final Request request = new Request.Builder().url(url).post(requestBody).build();return mOkHttpClient.newCall(request).execute();}/*** 同步基于post的文件上传* @param url 地址* @param file 提交的文件* @param fileKey 提交的文件key* @return Response*/public Response uploadSync(String url, File file, String fileKey) throws IOException {return uploadSync(url, new File[]{file}, new String[]{fileKey}, new Param[0]);}/*** 同步基于post的文件上传* @param url 地址* @param files 提交的文件数组* @param fileKeys 提交的文件数组key* @param params 提交的键值对* @return Response*/public Response uploadSync(String url, File[] files, String[] fileKeys, Param[] params) throws IOException {final RequestBody requestBody = buildMultipartFormRequestBody(files, fileKeys, params);final Request request = new Request.Builder().url(url).post(requestBody).build();return mOkHttpClient.newCall(request).execute();}//*** 异步get请求** @param url 地址* @param callback 回调*/public void getAsync(final String url, final OKHttpUICallback.ResultCallback callback)throws IOException {final Request request = new Request.Builder().url(url).build();final Call call = mOkHttpClient.newCall(request);deliveryResult(call, callback);}/*** post异步请求,键值对* @param url :地址* @param params :参数* @param callback :回调*/public void postAsync(String url, OKHttpUICallback.ResultCallback callback, Param... params) throws IOException {final Call call = mOkHttpClient.newCall(buildPostRequst(url, params));deliveryResult(call,callback);}/*** post异步请求,键值对* @param url :地址* @param params :参数* @param callback :回调*/public void postAsync(String url, OKHttpUICallback.ResultCallback callback, Map<String,String> params) throws IOException {final Call call = mOkHttpClient.newCall(buildPostRequst(url, params));deliveryResult(call,callback);}/*** post异步请求,提交Json数据** @param url 地址* @param json json格式的字符串*/public void postAsyncJson(String url, String json, OKHttpUICallback.ResultCallback callback) throws IOException {final RequestBody requestBody = RequestBody.create(JSON_TYPE, json);final Request request = new Request.Builder().url(url).post(requestBody).build();deliveryResult(mOkHttpClient.newCall(request),callback);}interface MyCallback{void onSuccess(String result);void onFailture();}public void postAsyncJsonn(String url, String json, MyCallback mCallback) throws IOException {final RequestBody requestBody = RequestBody.create(JSON_TYPE, json);final Request request = new Request.Builder().url(url).post(requestBody).build();deliveryResult(mOkHttpClient.newCall(request),mCallback);}private void deliveryResult(final Call call, final MyCallback mCallback){call.enqueue(new Callback() {@Overridepublic void onFailure(final Call call, final IOException e) {okHttpHandler.post(new Runnable() {@Overridepublic void run() {if (mCallback !=null){mCallback.onFailture();}}});}@Overridepublic void onResponse(Call call, final Response response) throws IOException {final String responseStr = response.body().string();okHttpHandler.post(new Runnable() {@Overridepublic void run() {if (mCallback != null) {mCallback.onSuccess(responseStr);}}});}});}/*** 生成request* @param url* @param params* @return*/private Request buildPostRequst(String url, Param... params){if(params == null){params = new Param[0];}FormBody.Builder builder = new FormBody.Builder();for(Param param:params){builder.add(param.key,param.value);}return new Request.Builder().url(url).post(builder.build()).build();}/*** 生成request* @param url* @param params* @return*/private Request buildPostRequst(String url, Map<String,String> params){Request request = null;if(params == null){params = new HashMap<>();}if(params != null){Set<Map.Entry<String,String>> entries = params.entrySet();FormBody.Builder builder = new FormBody.Builder();for(Map.Entry<String,String> entry:entries){builder.add(entry.getKey(),entry.getValue());}request = new Request.Builder().url(url).post(builder.build()).build();}return request;}/*** 生成post提交时的分块request* @param files* @param fileKeys* @param params* @return*/private RequestBody buildMultipartFormRequestBody(File[] files, String[] fileKeys, Param[] params){if(params == null){params = new Param[0];}MultipartBody.Builder builder = new MultipartBody.Builder();for(Param param:params){builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),RequestBody.create(null, param.value));}if(files == null){files = new File[0];}if(fileKeys == null){fileKeys = new String[0];}if(fileKeys.length != files.length){throw new ArrayStoreException("fileKeys.length != files.length");}RequestBody fileBody = null;int length = files.length;for(int i = 0;i<length;i++){File file = files[i];String fileName = file.getName();fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)),file);//TODO 根据文件名设置contentTypebuilder.addPart(Headers.of("Content-Disposition","form-data; name=\"" + fileKeys[i] + "\"; fileName=\"" + fileName + "\""),fileBody);}return builder.build();}private String guessMimeType(String path){FileNameMap fileNameMap = URLConnection.getFileNameMap();String type = fileNameMap.getContentTypeFor(path);if(type == null){type = "application/octet-stream";}return type;}/*** 获取文件名** @param path*/private String getFileName(String path){int lastSeparaorIndex = path.lastIndexOf("/");return (lastSeparaorIndex < 0) ? path : path.substring(lastSeparaorIndex + 1, path.length());}/*** 数据请求并处理* @param call* @param callback*/private void deliveryResult(final Call call, final OKHttpUICallback.ResultCallback callback){call.enqueue(new Callback() {@Overridepublic void onFailure(final Call call, final IOException e) {okHttpHandler.post(new Runnable() {@Overridepublic void run() {if (callback != null) {callback.onError(call, e);}}});}@Overridepublic void onResponse(Call call, Response response) throws IOException {if(callback != null){final Object object = JSON.parseObject(response.body().string(), callback.mType);okHttpHandler.post(new Runnable() {@Overridepublic void run() {callback.onSuccess(object);}});}}});}public static final class Param{private String key;private String value;public Param(String key, String value){this.key = key;this.value = value;}}
}
OKHttpUICallback
package com.example.administrator.myapplication;import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;import okhttp3.Call;
import okhttp3.Response;/*** Created by safly on 2016/9/1.** 回调主线程的接口*/
public class OKHttpUICallback {/*** 异步回调接口*/public static abstract class ResultCallback<T>{public Type mType;public ResultCallback(){mType = getSuperclassTypeParameter(getClass());}private static Type getSuperclassTypeParameter(Class<?> subclass){Type superclass = subclass.getGenericSuperclass();if(superclass instanceof Class){throw new RuntimeException("Miss type parameter");}ParameterizedType parameterizedType = (ParameterizedType)superclass;return parameterizedType.getActualTypeArguments()[0];}public abstract void onSuccess(T result);public abstract void onError(Call call, IOException e);}/*** 带有进度的上传、下载回调接口*/public interface ProgressCallback{void onSuccess(Call call, Response response, String path);void onProgress(long byteReadOrWrite, long contentLength, boolean done);void onError(Call call, IOException e);}
}
Result
package utils;/*** {"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001}*/
public class Result {private String resultcode;private String reason;private String result;private int error_code;public Result(String resultcode, String reason, String result, int error_code) {this.resultcode = resultcode;this.reason = reason;this.result = result;this.error_code = error_code;}public Result() {}@Overridepublic String toString() {return "Result{" +"resultcode='" + resultcode + '\'' +", reason='" + reason + '\'' +", result='" + result + '\'' +", error_code=" + error_code +'}';}public String getResultcode() {return resultcode;}public String getReason() {return reason;}public String getResult() {return result;}public int getError_code() {return error_code;}public void setResultcode(String resultcode) {this.resultcode = resultcode;}public void setReason(String reason) {this.reason = reason;}public void setResult(String result) {this.result = result;}public void setError_code(int error_code) {this.error_code = error_code;}
}
这篇关于OkHttp学习(1)--同步和异步(get、post键值对、post带map、请求头体封装json)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!