Android OkHttp的封装使用

1.先看原始的请求过程

以下是请求过程的使用示例。

private void useOkHttpSendRequest(){
	
	OkHttpClient client = new OkHttpClient();
	RequestBody body = new FormBody.Builder()
		.add("InfoOne", mInfoOneEditText.getText().toString())
		.add("InfoTwo", mInfoTwoEditText.getText().toString)
		.build();
	final Request request = new Request.Builder().url(UrlCons.YOUR_URL).post(body).build();
	Call call = client.newCall(request);
	call.enqueue(new Callback() {

		@Override
		public void onFailure(Call call, IOException e){
		}

		@Override
		public void onResponse(Call call, Response response) throws IOException{

			if (response.isSuccessful()) {
				//This is in the sub-thread, we shuold transport the data to the main thread
				String responseBody = response.body().string();
			}
		}
	});
}

没有封装的方法不好用。需要进行封装。

在APP中可以创建全局变量,使整个APP都用这个变量。参考:https://www.cnblogs.com/maoIT/p/3835833.html

如下:

此时对其进行封装,新建几个类。

//The class to deal with the OkHttpCallback
public abstract class OkHttpCallBack implements CallBack{

	public abstract void onSuccess(final Call call, JSONObject jsonObject);
		
	@Override
	public void onResponse(Call call, Response response) throws IOException{

		if (response != null) {
			if (response.isSuccessful()) {
				try{
					String str = response.body().string().trim();
					JSONObject object = (JSONObject)new JSONTokener(str).nextValue();
					if (object != null) {
						onSuccess(call, object);
					}els{
						onFailure(call, null);
					}
				}catch{
					e.printStackTrace();
				}

			}else{
				onFailure(call, null);
			}
		}
	}


	@Override
	public void onFailure(Call call, IOException e){

	}
}
//OkHttp Core Class
public class OkHttpUtil{
	private static OkHttpClient mOkHttpClient = null;

	//Call this method in the Application class. ---> onCreate() method.
	//Thus we can get only one instance of httpClient in the whole app. 
	public static void init(){
		if (mOkHttpClient == null) {
			OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
				.connectTimeout(5000, TimeUnit.MILLISECOND)
				.readTimeout(5000, TimeUnit.MILLISECOND)
				.writeTimeout(5000, TimeUnit.MILLISECOND);
			mOkHttpClient = builder.build();	
		}
	}


	//If GET method needs some other params, just need to add a HaspMap. Refer to:https://www.imooc.com/video/18685
	public static void get(String url, OkHttpCallback okHttpCallback){
		Call call = null;

		try{
			Request request = new Request.Builder().url(url).build();
			call = mOkHttpClient.newCall(request);
			call.enqueue(okHttpCallback);

		}catch(IOException ex){
			ex.printStackTrace();
		}
	}


	public static void post(String url, OkHttpCallback okHttpCallback, HashMap<String, String> bodyMap){
		Call call = null;

		try{

			FormBody.Builder builder = new FormBody.Builder();
			for (HashMap.Entry<String, String> entry : bodyMap.entrySet()) {
				builder.add(entry.getKey(), entry.getValue());
			}
			RequestBody body = builder.build();

			Request request = new Request.Builder().post(body).url(url).build();
			call = mOkHttpClient.newCall(request);
			call.enqueue(okHttpCallback);

		}catch(IOException ex){
			ex.printStackTrace();
		}
	}

}
public  abstract class ApiUtil {

	private ApiListener mApiListener = null;
	private String mStatus;

	private OkHttpCallback mSendListener = new OkHttpCallback(){

		@Override
		public void onSuccess(Call call, Response response){
			mStatus = response.optString("status");
			if (isSuccess()) {
				try{
					parseData(response);
					mApiListener.success(ApiUtil.this);

				}catch(IOException e){
					e.printStackTrace();
				}
				
			}else{
				mApiListener.failrure(ApiUtil.this);
			}
		}

		@Override
		public void onFailure(Call call, IOException e){
			mApiListener.failrure(ApiUtil.this);
		}
	}

	public boolean isSuccess(){
		return "0".equals(mStatus) || "200".equals(mStatus); 
	}

	protected abstract void parseData(JSONObject jsonObject) throws Exception;

	protected abstract String getUrl();

	//Send GET request
	//Listener: Tell the app whether the GET reqeust is success.
	private void get(ApiListener listener){
		mApiListener = listener;
		OkHttpUtil.get(getUrl(), mSendListener);
	}


	private HashMap<String, String> mBodyMap = new HashMap<>();
	public void addParams(String key, String value){
		mBodyMap.put(key, value);
	}


	//Send POST request
	//Listener: Tell the app whether the POST reqeust is success.
	private void post(ApiListener listener){
		mApiListener = listener;
		OkHttpUtil.post(getUrl(), mSendListener, mBodyMap);
	}

}
public interface ApiListener {

	//Request success
	void succss(ApiUtil apiUtil);

	//Request failed
	void failrure(ApiUtil apiUtil);


}

以下是测试GET的API

public class TestGetBookApi extends ApiUtil{

	public String mResponse;

	@Override
	protected String getUrl(){
		return Url.IP + "/api/v1/books";
	}

	protected void parseData(JSONObject jsonObject){
		mResponse = jsonObject.toString();
	}
}

以下是POST的API

public class TestPostBookApi extends ApiUtil{

	public String mResponse;

	public TestGetBookApi(String bookName, String bookInfo){
		addParams("bookName", bookName);
		addParams("bookInfo", bookInfo);
	}
	
	@Override
	protected String getUrl(){
		return Url.IP + "/api/v1/books";
	}

	protected void parseData(JSONObject jsonObject){
		mResponse = jsonObject.toString();
	}
}

以下是在Activity中进行调用测试

//Use the api

public class TestActivity extends Activity{

	private void processGetApi(){

		new TestGetBookApi().get(new ApiListener() {

			@Override
			public void success(ApiUtil apiUtil){
				TestGetBookApi api = (TestGetBookApi)apiUtil;
				String response = api.mResponse;
				parseResponse(response);
			}

			@Override void failrure(ApiUtil apiUtil){

			}


		});
	};

	//The parse the response
	public void parseResponse(Response response){

	}

	private void processPostApi(){
		new TestPostBookApi(mBookNameEdit.getText().toString(),
			mBookInfoEdit.getText().toString()).post(new ApiListener(){
				@Override
				public void success(ApiUtil apiUtil){
					Log.d(TAG, "---apiUtil = " + apiUtil);
				}

				@Override void failrure(ApiUtil apiUtil){

			}

		});
	}

}

详细博客参考来源:https://www.imooc.com/video/18688

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值