特点:
1)支持SPDY协议,共享一个socket来处理同一个服务器的所有请求。
2)无缝支持GZIP,来减少数据流量。
3)缓存相应数据来减少重复的网络请求。
网络协议:
SPDY(读作“SPeeDY”)是Google开发的基于TCP的应用层协议,用以最小化网络延迟,提升网络速度,优化用户的网络使用体验。SPDY并不是一种用于替代HTTP的协议,而是对HTTP协议的增强。新协议的功能包括数据流的多路复用、请求优先级以及HTTP报头压缩。(应用层Http、网络层、传输层协议)
常用类:
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 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) {
}
});
}
}
注意事项:
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 params, BaseCallBack baseCallBack) {
Request request = buildRequest(url, params, HttpMethodType.POST);
sendRequest(request, baseCallBack);
}
/**
* 1)获取Request对象
*
* @param url
* @param params
* @param httpMethodType 请求方式不同,Request对象中的内容不一样
* @return Request 必须要返回Request对象, 因为发送请求的时候要用到此参数
*/
private Request buildRequest(String url, HashMap 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 param) {
FormEncodingBuilder builder = new FormEncodingBuilder();
//遍历HashMap集合
if (param != null && !param.isEmpty()) {
Set> entries = param.entrySet();
for (Map.Entry 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;
}
}