国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > 综合技术 > 以OKHttp为基础封装网络请求工具类

以OKHttp为基础封装网络请求工具类

来源:程序员人生   发布时间:2016-09-26 08:54:49 阅读次数:2735次

特点:

1)支持SPDY协议,同享1个socket来处理同1个服务器的所有要求。

2)无缝支持GZIP,来减少数据流量。

3)缓存相应数据来减少重复的网络要求。

 

网络协议:

SPDY(读作“SPeeDY”)是Google开发的基于TCP的利用层协议,用以最小化网络延迟,提升网络速度,优化用户的网络使用体验SPDY其实不是1种用于替换HTTP的协议,而是对HTTP协议的增强。新协议的功能包括数据流的多路复用、要求优先级和HTTP报头紧缩。(利用层Http、网络层、传输层协议) <Volley框架实使用了spdy协议>

 

经常使用类:

OKHttpClient(客户端对象)、

Request(访问要求)、 RequestBody(要求实体对象)

Response(响应类)、 ResponseBody(响应结果类)

FormEncodingBuilder(表单构造器)、

MediaType(数据类型)

 

response.isSuccessful() response.body().string()

client.newCall(request)


Activity中的代码:

package com.crs.demo.ui.okhttp; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.crs.demo.R; import com.crs.demo.base.BaseActivity; import com.crs.demo.constant.UrlConstant; import com.google.gson.Gson; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.HashMap; /** * Created on 2016/9/19. * Author:crs * Description:OKHttp网络要求框架的使用 */ public class OKHttpActivity extends BaseActivity implements View.OnClickListener { private Button btn_ok_http_get; private Button btn_ok_http_post; private TextView tv_ok_http_content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_okhttp); initViews(); initListener(); } private void initViews() { btn_ok_http_get = findView(R.id.btn_ok_http_get); btn_ok_http_post = findView(R.id.btn_ok_http_post); tv_ok_http_content = findView(R.id.tv_ok_http_content); } private void initListener() { btn_ok_http_get.setOnClickListener(this); btn_ok_http_post.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_ok_http_get: { clickGet(); } break; case R.id.btn_ok_http_post: { clickPost(); } break; } } private void clickPost() { HttpUtils httpUtils = new HttpUtils(); HashMap<String, String> params = new HashMap<>(); params.put("orderNo", "TH01587458"); httpUtils.post(UrlConstant.ORDER_STATUS_POST, params, new HttpUtils.BaseCallBack() { @Override public void onSuccess(Response response, String json) { JSONObject jsonObject; try { jsonObject = new JSONObject(json); String status = jsonObject.getString("Status"); tv_ok_http_content.setText(status); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFail(Request request, IOException e) { } @Override public void onError(Response response, int code) { } }); } private void clickGet() { HttpUtils httpUtils = new HttpUtils(); httpUtils.get(UrlConstant.ORDER_STATUS, new HttpUtils.BaseCallBack() { @Override public void onSuccess(Response response, String json) { //使用json包解析 注意注解的使用 Gson gson = new Gson(); { Entity entity = gson.fromJson(json, Entity.class); AfterSaleType afterSaleType = entity.getAfterSaleType(); String shopService = afterSaleType.getShopService(); tv_ok_http_content.setText(shopService); } //只能使用内部类的情势去封装对象,这样就不会报错 { //ResponseEntity responseEntity = gson.fromJson(json, ResponseEntity.class); //ResponseEntity.AfterSaleType afterSaleType = responseEntity.getAfterSaleType(); //String shopService = afterSaleType.getShopServiceTousu(); //tv_ok_http_content.setText(shopService); } } @Override public void onFail(Request request, IOException e) { } @Override public void onError(Response response, int code) { } }); } }


网络要求工具类HttpUtils中的代码

注意事项:

1)接口回调(回调结果到Activity中)。

2)子线程与主线程通讯。

3)OKHttp的两个使用步骤。

package com.crs.demo.ui.okhttp; import android.os.Handler; import android.os.Looper; import com.crs.demo.constant.IntConstant; import com.crs.demo.utils.OKHttpUtils; import com.google.gson.Gson; import com.squareup.okhttp.Callback; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Created on 2016/9/19. * Author:crs * Description:网络要求工具类的封装 */ public class HttpUtils { private OkHttpClient client; private Handler mHandler; public HttpUtils() { client = new OkHttpClient(); //设置连接超时时间,在网络正常的时候有效 client.setConnectTimeout(IntConstant.REQUEST_TIME_OUT, TimeUnit.SECONDS); //设置读取数据的超时时间 client.setReadTimeout(IntConstant.REQUEST_TIME_OUT, TimeUnit.SECONDS); //设置写入数据的超时时间 client.setWriteTimeout(IntConstant.REQUEST_TIME_OUT, TimeUnit.SECONDS); //Looper.getMainLooper() 获得主线程的消息队列 mHandler = new Handler(Looper.getMainLooper()); } public void get(String url, BaseCallBack baseCallBack) { Request request = buildRequest(url, null, HttpMethodType.GET); sendRequest(request, baseCallBack); } public void post(String url, HashMap<String, String> params, BaseCallBack baseCallBack) { Request request = buildRequest(url, params, HttpMethodType.POST); sendRequest(request, baseCallBack); } /** * 1)获得Request对象 * * @param url * @param params * @param httpMethodType 要求方式不同,Request对象中的内容不1样 * @return Request 必须要返回Request对象, 由于发送要求的时候要用到此参数 */ private Request buildRequest(String url, HashMap<String, String> params, HttpMethodType httpMethodType) { //获得辅助类对象 Request.Builder builder = new Request.Builder(); builder.url(url); //如果是get要求 if (httpMethodType == HttpMethodType.GET) { builder.get(); } else { RequestBody body = buildFormData(params); builder.post(body); } //返回要求对象 return builder.build(); } /** * 2)发送网络要求 * * @param request * @param baseCallBack */ private void sendRequest(Request request, final BaseCallBack baseCallBack) { client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { callBackFail(baseCallBack,request, e); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String json = response.body().string(); //此时要求结果在子线程里面,如何把结果回调到主线程里? callBackSuccess(baseCallBack,response, json); } else { callBackError(baseCallBack,response, response.code()); } } }); } /** * 主要用于构建要求参数 * * @param param * @return ResponseBody */ private RequestBody buildFormData(HashMap<String, String> param) { FormEncodingBuilder builder = new FormEncodingBuilder(); //遍历HashMap集合 if (param != null && !param.isEmpty()) { Set<Map.Entry<String, String>> entries = param.entrySet(); for (Map.Entry<String, String> entity : entries) { String key = entity.getKey(); String value = entity.getValue(); builder.add(key, value); } } return builder.build(); } //要求类型定义 private enum HttpMethodType { GET, POST } //定义回调接口 public interface BaseCallBack { void onSuccess(Response response, String json); void onFail(Request request, IOException e); void onError(Response response, int code); } //主要用于子线程和主线程进行通讯 private void callBackSuccess(final BaseCallBack baseCallBack, final Response response, final String json){ mHandler.post(new Runnable() { @Override public void run() { baseCallBack.onSuccess(response,json); } }); } private void callBackError(final BaseCallBack baseCallBack, final Response response, final int code){ mHandler.post(new Runnable() { @Override public void run() { baseCallBack.onError(response,code); } }); } private void callBackFail(final BaseCallBack baseCallBack, final Request request, final IOException e){ mHandler.post(new Runnable() { @Override public void run() { //相当于此run方法是在主线程履行的,可以进行更新UI的操作 baseCallBack.onFail(request,e); } }); } }

实体模型的封装

注意事项: 

1)使用注解@SerializedName("Code") 修改字段名

2)不要使用内部类嵌套的情势封装实体模型

Entity模型

package com.crs.demo.ui.okhttp; import com.google.gson.annotations.SerializedName; /** * Created on 2016/9/19. * Author:crs * Description:要求结果实体模型 */ public class Entity { @SerializedName("Code") private String code; @SerializedName("AfterSaleType") private AfterSaleType afterSaleType; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public AfterSaleType getAfterSaleType() { return afterSaleType; } public void setAfterSaleType(AfterSaleType afterSaleType) { this.afterSaleType = afterSaleType; } }

AfterSaleType模型:

package com.crs.demo.ui.okhttp; import com.google.gson.annotations.SerializedName; /** * Created on 2016/9/19. * Author:crs * Description:AfterSaleType实体模型 */ public class AfterSaleType { @SerializedName("UnReceive") private String unReceive; @SerializedName("returnGoods") private String ReturnGoods; @SerializedName("ShopServiceTousu") private String ShopService; @SerializedName("ProductQuality") private String productQuality; @SerializedName("Invoice") private String invoice; @SerializedName("Other") private String other; public String getUnReceive() { return unReceive; } public void setUnReceive(String unReceive) { this.unReceive = unReceive; } public String getReturnGoods() { return ReturnGoods; } public void setReturnGoods(String returnGoods) { ReturnGoods = returnGoods; } public String getShopService() { return ShopService; } public void setShopService(String shopService) { ShopService = shopService; } public String getProductQuality() { return productQuality; } public void setProductQuality(String productQuality) { this.productQuality = productQuality; } public String getInvoice() { return invoice; } public void setInvoice(String invoice) { this.invoice = invoice; } public String getOther() { return other; } public void setOther(String other) { this.other = other; } }

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生