Android M (6.x) tutorial for parsing and sending JSON requests using the OKHTTP package _android

Source: Internet
Author: User
Tags connection pooling reflection

About Android 6.0
Android old version network request:
1,httpurlconnection
2,apache Http Client
Android6.0 Version Network request:
1,httpurlconnection
2,okhttp
Android6.0 version of the old network abandoned the request, then what is its advantage?
1, support Spdy, share the same socket to handle all requests of the same server
2, if Spdy is not available, reduce request latency through connection pooling
3, seamless support for gzip to reduce data traffic
4, cache response data to reduce duplicate network requests

Post request sent to server JSON:

Let's take a look at a sample and send a detailed request to us below.

public class Mainactivity extends appcompatactivity {public static final String TAG = ' mainactivity '; public static fin Al mediatype Json=mediatype.parse ("Application/json;
Charset=utf-8 ");
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.activity_main);
Open a thread, do networking operation new Thread () {@Override public void run () {Postjson ();}}.start ();
 private void Postjson () {//affirm to pass a JSON string to the server///Create a Okhttpclient object okhttpclient okhttpclient = new Okhttpclient ();
 Create a Requestbody (parameter 1: The JSON string passed by data type parameter 2) requestbody requestbody = Requestbody.create (JSON, JSON); Create a Request object requests = new Request.builder (). URL ("Http://192.168.0.102:8080/TestProject/JsonServlet"). Post (
 requestbody). build ();
  Send request Get response try {Response Response=okhttpclient.newcall (Request). Execute ();

  Determine if the request was successful if (Response.issuccessful ()) {\//Print Service side returns results LOG.I (Tag,response.body (). String ()); catch (IoexcePtion e) {e.printstacktrace ();

 }

}

}

SPDY (read as "SPeeDY") is a TCP based application layer protocol developed by Google to minimize network latency, improve network speed, and optimize the user's network usage experience. Spdy is not a protocol to replace HTTP, but an enhancement to the HTTP protocol. Features of the new protocol include multiplexing of data streams, request priority, and HTTP header compression. Google said that after the introduction of the Spdy protocol, the page loading rate in the lab test was 64% faster than the original.
The zip was first created by Jean-loup Gailly and Mark Adler to Unⅸ file compression for the system. We often use the file suffix. gz in Linux, which is the gzip format. Today has become a very popular data compression format, or a file format, used on the Internet.
The gzip encoding on the HTTP protocol is a technique used to improve the performance of Web applications. Large-volume Web sites often use gzip compression technology to allow users to experience faster speeds. This is generally referred to as a feature installed in the WWW server, when someone comes to the Web site in this server, this function in the server will compress the content of the Web page and transmit it to the visiting Computer browser. Generally, plain text content can be compressed to 40% of the original size. So the transmission is fast, The effect is that you click on the URL will be quickly displayed. Of course, this also increases the load on the server. The function module is installed in the general server.

JSON parsing
Here we will use JSON unified generic parsing, and some Java reflection mechanism to resolve generic object class<?>
1. First we declare that a Typeinfo.java class is used to encapsulate generic-related attributes

Import Java.lang.reflect.Array;
Import Java.lang.reflect.GenericArrayType;
Import Java.lang.reflect.ParameterizedType;

Import Java.lang.reflect.Type;
 public class TypeInfo {//type generic object type private class<?> componenttype;
 Type belongs to object types 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, Componenttyp
 e);
 public static TypeInfo Createnormaltype (class<?> componenttype) {return new TypeInfo (null, componenttype); public static TypeInfo Createparameterizedtype (class<?> rawtype, class<?> componenttype) {return new Ty
 Peinfo (Rawtype, ComponentType);
  Public typeinfo (Type type) {this.type = type;
   The IF (type instanceof Parameterizedtype) {//Returns a type object representing a class or interface declaring this type. This.rawtype = (CLASS&Lt;?
   >) ((parameterizedtype) type). Getrawtype ();
   Getactualtypearguments () returns an array of type objects that represent the actual type parameters of this type.
   Type[] actualtypearguments = (parameterizedtype) type). Getactualtypearguments ();
   This.componenttype = (class<?>) actualtypearguments[0];

  Typereference=new typereference<map<componenttype,componenttype>> () {};
   else if (type instanceof Genericarraytype) {//Returns a type object representing a class or interface declaring this type.
   This.rawtype = Array.class; Indicates that an element type is an array type This.componenttype = (class<?>) (Genericarraytype) type of a parameterized type or a type variable. getgenericcomponenttype
  ();
  else {This.componenttype = (class<?>) type;
 The public Type GetType () {return type;
 Public class<?> Getcomponenttype () {return componenttype;
 Public class<?> Getrawtype () {return rawtype;

 }

}

2. Declares that the Reqclassutils.java class is used to get the typeinfo of a generic object through the reflection mechanism

 import java.lang.reflect.ParameterizedType; import Java.lang.reflect.Type; public class Reqclassutils {public static typeinfo Getcallbackgenerictype (class<?> clazz) {//Get parent class type with generic type Genericsuperclass = Clazz.getgenericsuperclass ();//type is a public advanced interface of all types in the Java programming language.
  They include the original type, the parameterized type, the array type, the type variable, and the base type.
  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 Gets an array of parameterized types, the generics may have more than one type[] args = ((parameterizedtype) type). Getactualtypearguments ();
   if (args!= null && args.length > 0) {return new TypeInfo (args[0));
 } return null; }
}

3. The next point is to declare a JSON parsing tool class Reqjsonutils.java, which is primarily used to parse different types of JSON resolution by TypeInfo related properties

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 {//Basic type mapping relationship map private static final Map Primitivewrappertypemap = new HashMap (8);
  static {//Add basic type 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); /** * Converts a JSON string to the specified user return value type * * @param type * @param jsondata * @return * @throws jsonexception * * PublIC Static <T> T parsehttpresult (typeinfo type, String jsondata) throws Jsonexception {//handling the return value of void type if (void).
  Class.isassignablefrom (Type.getcomponenttype ()) {return null;
  //Gets the data type of the current type class<?> Rawtype = Type.getrawtype ();
  Is Array boolean isarray = Rawtype!= null && Array.class.isAssignableFrom (rawtype);
  Is Collection boolean iscollection = Rawtype!= null && Collection.class.isAssignableFrom (rawtype);
  Is the Map boolean isMap = Rawtype!= null && Map.class.isAssignableFrom (rawtype);
  Gets the generic type class<?> ComponentType = Type.getcomponenttype ();
  Declares the result object T results = null;
  if (iscollection) {//Process collection result = (T) json.parsearray (Jsondata, ComponentType);
  else if (IsArray) {//process array result = (T) json.parsearray (Jsondata, ComponentType). ToArray ();
  else if (ISMAP) {//Process map result = (T) jsonobject.parseobject (Jsondata, Type.GetType ()); else if (Componenttype.isassignablefrom (striNg.class)) {//processing string return value returns (T) Jsondata; If the return type of the else {//interface is a simple type, it is encapsulated as a JSON object, and the real object is stored on the Value property if (Isprimitiveorwrapper (ComponentType)) {result = (
   T) parseobject (jsondata);
   else {//Process custom Object result = (T) parseobject (Jsondata, ComponentType);
 } return result;
  /** * To determine if it is the basic data type * * @param clazz * @return/public static Boolean Isprimitiveorwrapper (Class clazz) {
 Return (clazz.isprimitive () | | | isprimitivewrapper (CLAZZ)); /** * Determine if it is a basic data type * * @param clazz * @return/public static Boolean Isprimitivewrapper (Class clazz) {R
 Eturn Primitivewrappertypemap.containskey (Clazz);

 }
}

How to use it?
1. Implementation resolution

 TypeInfo TypeInfo = Reqclassutils.getcallbackgenerictype (Callback.getclass ());
 Callback.onreqsuccess (Reqjsonutils.parsehttpresult (TypeInfo, jsondata));

2. Send Request

  hashmap<string, string> paramsmap = new hashmap<> ();
  Paramsmap.put ("SourceType", "2");
  Paramsmap.put ("Sourcedesc", "[Android]" + Build.VERSION.RELEASE + "[Mobel]" + Build.brand + "" + Build.model + Build.devi CE);
  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. Type of support

  New reqcallback<list<object>> ()//collection collection
  new reqcallback<map<string, user>> (); /map
  new reqcallback<void> ();//void
  new reqcallback<long> ();//underlying type

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.