当前位置: 移动技术网 > IT编程>移动开发>Android > Android M(6.x)使用OkHttp包解析和发送JSON请求的教程

Android M(6.x)使用OkHttp包解析和发送JSON请求的教程

2019年07月24日  | 移动技术网IT编程  | 我要评论

杀手47高清,热气球婚礼,又名锦州站长网

关于android 6.0
android老版本网络请求:
1,httpurlconnection
2,apache http client
android6.0版本网络请求:
1,httpurlconnection
2,okhttp
android6.0版本废弃了老的网络请求,那么它的优势是什么呢?
1,支持spdy,共享同一个socket来处理同一个服务器的所有请求
2,如果spdy不可用,则通过连接池来减少请求延时
3,无缝的支持gzip来减少数据流量
4,缓存响应数据来减少重复的网络请求

post请求发送给服务器json:

我们先来看一个样例,详细的请求发送我们下面还会讲.

public class mainactivity extends appcompatactivity {

public static final string tag = "mainactivity";
public static final mediatype json=mediatype.parse("application/json; charset=utf-8");
@override
protected void oncreate(bundle savedinstancestate) {
 super.oncreate(savedinstancestate);
 setcontentview(r.layout.activity_main);
 //开启一个线程,做联网操作
 new thread() {
  @override
  public void run() {

   postjson();
  }
 }.start();
}

 private void postjson() {
 //申明给服务端传递一个json串
 //创建一个okhttpclient对象
 okhttpclient okhttpclient = new okhttpclient();
 //创建一个requestbody(参数1:数据类型 参数2传递的json串)
 requestbody requestbody = requestbody.create(json, json);
 //创建一个请求对象
 request request = new request.builder()
   .url("http://192.168.0.102:8080/testproject/jsonservlet")
   .post(requestbody)
   .build();
 //发送请求获取响应
 try {
 response response=okhttpclient.newcall(request).execute();
  //判断请求是否成功
  if(response.issuccessful()){\
   //打印服务端返回结果
   log.i(tag,response.body().string());

  }
 } catch (ioexception e) {
  e.printstacktrace();
 }

}

}

spdy(读作“speedy”)是google开发的基于tcp的应用层协议,用以最小化网络延迟,提升网络速度,优化用户的网络使用体验。spdy并不是一种用于替代http的协议,而是对http协议的增强。新协议的功能包括数据流的多路复用、请求优先级以及http报头压缩。谷歌表示,引入spdy协议后,在实验室测试中页面加载速度比原先快64%。
zip最早由jean-loup gailly和mark adler创建,用于unⅸ系统的文件压缩。我们在linux中经常会用到后缀为.gz的文件,它们就是gzip格式的。现今已经成为internet 上使用非常普遍的一种数据压缩格式,或者说一种文件格式。
http协议上的gzip编码是一种用来改进web应用程序性能的技术。大流量的web站点常常使用gzip压缩技术来让用户感受更快的速度。这一般是指www服务器中安装的一个功能,当有人来访问这个服务器中的网站时,服务器中的这个功能就将网页内容压缩后传输到来访的电脑浏览器中显示出来.一般对纯文本内容可压缩到原大小的40%.这样传输就快了,效果就是你点击网址后会很快的显示出来.当然这也会增加服务器的负载. 一般服务器中都安装有这个功能模块的。

json解析
这里我们将采用json统一泛型解析,与一些java的反射机制来解析泛型对象class<?>:
1.首先我们声明一个typeinfo.java类用来封装泛型相关属性

import java.lang.reflect.array;
import java.lang.reflect.genericarraytype;
import java.lang.reflect.parameterizedtype;
import java.lang.reflect.type;

public class typeinfo {
 //type泛型对象类型
 private class<?> componenttype;
 //type所属对象类型
 private class<?> rawtype;
 //type
 private type type;

 private typeinfo(class<?> rawtype, class<?> componenttype) {

  this.componenttype = componenttype;
  this.rawtype = rawtype;
 }

 public static typeinfo createarraytype(class<?> componenttype) {
  return new typeinfo(array.class, componenttype);
 }

 public static typeinfo createnormaltype(class<?> componenttype) {
  return new typeinfo(null, componenttype);
 }

 public static typeinfo createparameterizedtype(class<?> rawtype, class<?> componenttype) {
  return new typeinfo(rawtype, componenttype);
 }

 public typeinfo(type type) {
  this.type = type;
  if (type instanceof parameterizedtype) {
   //返回 type 对象,表示声明此类型的类或接口。
   this.rawtype = (class<?>) ((parameterizedtype) type).getrawtype();
   //getactualtypearguments()返回表示此类型实际类型参数的 type 对象的数组。
   type[] actualtypearguments = ((parameterizedtype) type).getactualtypearguments();
   this.componenttype = (class<?>) actualtypearguments[0];
   // typereference=new typereference<map<componenttype,componenttype>>(){};

  } else if (type instanceof genericarraytype) {
   //返回 type 对象,表示声明此类型的类或接口。
   this.rawtype = array.class;
   // 表示一种元素类型是参数化类型或者类型变量的数组类型
   this.componenttype = (class<?>) ((genericarraytype) type).getgenericcomponenttype();
  } else {
   this.componenttype = (class<?>) type;
  }
 }

 public type gettype() {
  return type;
 }

 public class<?> getcomponenttype() {
  return componenttype;
 }


 public class<?> getrawtype() {
  return rawtype;
 }

}

2.声明reqclassutils.java类 用于通过反射机制获取泛型对象的typeinfo

import java.lang.reflect.parameterizedtype;
import java.lang.reflect.type;

public class reqclassutils {

 public static typeinfo getcallbackgenerictype(class<?> clazz) {
  //获得带有泛型的父类
  type genericsuperclass = clazz.getgenericsuperclass();//type是 java 编程语言中所有类型的公共高级接口。它们包括原始类型、参数化类型、数组类型、类型变量和基本类型。
  typeinfo type = getgetnerictype(genericsuperclass);
  if (type == null) {
   type[] genericinterfaces = clazz.getgenericinterfaces();
   if (genericinterfaces != null && genericinterfaces.length > 0) {
    type = getgetnerictype(genericinterfaces[0]);
   }
  }
  return type;
 }

 private static typeinfo getgetnerictype(type type) {
  if (type != null && type instanceof parameterizedtype) {
   //getactualtypearguments获取参数化类型的数组,泛型可能有多个
   type[] args = ((parameterizedtype) type).getactualtypearguments();
   if (args != null && args.length > 0) {
    return new typeinfo(args[0]);
   }
  }
  return null;
 }
}

3.接下来重点来了,声明一个json解析工具类reqjsonutils.java,主要用于通过typeinfo相关属性进行不同类型的json解析

import com.alibaba.fastjson.json;
import com.alibaba.fastjson.jsonexception;
import com.alibaba.fastjson.jsonobject;
import java.lang.reflect.array;
import java.util.collection;
import java.util.hashmap;
import java.util.map;

import static com.alibaba.fastjson.json.parseobject;

public class reqjsonutils {

 //基本类型映射关系map
 private static final map primitivewrappertypemap = new hashmap(8);

 static {
  //添加基本类型
  primitivewrappertypemap.put(boolean.class, boolean.class);
  primitivewrappertypemap.put(byte.class, byte.class);
  primitivewrappertypemap.put(character.class, char.class);
  primitivewrappertypemap.put(double.class, double.class);
  primitivewrappertypemap.put(float.class, float.class);
  primitivewrappertypemap.put(integer.class, int.class);
  primitivewrappertypemap.put(long.class, long.class);
  primitivewrappertypemap.put(short.class, short.class);
 }

 /**
  * 将json字符串转换成指定的用户返回值类型
  *
  * @param type
  * @param jsondata
  * @return
  * @throws jsonexception
  */
 public static <t> t parsehttpresult(typeinfo type, string jsondata) throws jsonexception {
  // 处理void类型的返回值
  if (void.class.isassignablefrom(type.getcomponenttype())) {
   return null;
  }
  //获取当前type的数据类型
  class<?> rawtype = type.getrawtype();
  //是否是array
  boolean isarray = rawtype != null && array.class.isassignablefrom(rawtype);
  //是否是collection
  boolean iscollection = rawtype != null && collection.class.isassignablefrom(rawtype);
  //是否是map
  boolean ismap = rawtype != null && map.class.isassignablefrom(rawtype);
  //获取泛型类型
  class<?> componenttype = type.getcomponenttype();
  //声明结果对象
  t result = null;
  if (iscollection) {//处理collection
   result = (t) json.parsearray(jsondata, componenttype);
  } else if (isarray) {//处理array
   result = (t) json.parsearray(jsondata, componenttype).toarray();
  } else if (ismap) {//处理map
   result = (t) jsonobject.parseobject(jsondata, type.gettype());
  } else if (componenttype.isassignablefrom(string.class)) {//处理字符串返回值
   return (t) jsondata;
  } else {
   // 接口的返回类型如果是简单类型,则会封装成为一个json对象,真正的对象存储在value属性上
   if (isprimitiveorwrapper(componenttype)) {
    result = (t) parseobject(jsondata);
   } else {
    //处理自定义对象
    result = (t) parseobject(jsondata, componenttype);
   }
  }
  return result;
 }

 /**
  * 判断是否是基本数据类型
  *
  * @param clazz
  * @return
  */
 public static boolean isprimitiveorwrapper(class clazz) {
  return (clazz.isprimitive() || isprimitivewrapper(clazz));
 }

 /**
  * 判断是否是基本数据类型
  *
  * @param clazz
  * @return
  */
 public static boolean isprimitivewrapper(class clazz) {
  return primitivewrappertypemap.containskey(clazz);
 }
}

如何使用?
1.实现解析

 typeinfo typeinfo = reqclassutils.getcallbackgenerictype(callback.getclass());
 callback.onreqsuccess(reqjsonutils.parsehttpresult(typeinfo, jsondata));

2.发送请求

  hashmap<string, string> paramsmap = new hashmap<>();
  paramsmap.put("sourcetype", "2");
  paramsmap.put("sourcedesc", "[android]" + build.version.release + "[mobel]" + build.brand + " " + build.model + build.device);
  hashmap<string, string> params = dealstringbody(paramsmap);
  requestmanager.getinstance(this).requestasyn("xxx/actionurl", requestmanager.type_post_json, params, new reqcallback<string>() {

   @override
   public void onreqsuccess(string result) {
    request_tv.settext(result);
   }

   @override
   public void onreqfailed(string errormsg) {

   }
  });

3.支持类型

  new reqcallback<list<object>>();//集合collection
  new reqcallback<map<string, user>>();//map
  new reqcallback<void>();//void
  new reqcallback<long>();//基础类型

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网