Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

OkHttp initiates network request and how to realize the conversion between JSON/XML and object

Shulou Source: shulou.com Published: 2022-06-02 03:02:26 09月11日 Update

This article introduces OkHttp to initiate network requests and how to achieve the conversion between JSON/XML and objects. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

1. Add okhttp,xtream,fastjson dependencies:

Tip: Qiniu jdk contains an old version of okhttp, which needs to be excluded first.

two。 Configure okHttpClient to allow spring to automatically assemble:

Put it into the configuration class labeled @ Configuration for unified management.

Automatic injection:

@ Resource

Private OkHttpClient okHttpClient

3. GET requests JSON data and encapsulates it into an object (record the location where the user logs in (HttpUtil.java):

OkHttpClient.newCall (request). Execute initiates a network request.

Request:

GET: new Request.Builder (). Url (url). Build ()

POST: RequestBody requestBody = new FormBody.Builder ()

.add ("key", "value")

.add ("key", "value")

.build ()

New Request.Builder () .post (requestBody) .url (url) .build ()

Use JSON.parseObject (jsonString,object) to encapsulate JSON into objects and support cascading properties.

Call Taobao IP address library: http://ip.taobao.com/service/getIpInfo2.php?ip=xxx, and return:

Get the real IP address of the client:

Reference: http://blog.csdn.net/z69183787/article/details/21187485

The returned information can be automatically encapsulated by abstracting it into a class:

Domain/json/IpLocation.java

Domain/Location.java

Location location = HttpUtil.getLocationByIP (request, okHttpClient)

4. GET requests XML data and encapsulates it into an object:

Tip: before using XStream to convert XML, you need to register the object.

XStream.processAnnotations (Class)

5. Object to JSON:

JSONObject.toJSONString (object)

6. Object to XML:

XStream.processAnnotations (class)

XStream.toXML (object)

Tip: sample source code springboot-thymeleaf: org/ramer/demo/controller/DemoController.java

Github: https://github.com/RamerF/spring-web.git

This is all about the network request initiated by OkHttp and how to realize the conversion between JSON/XML and object. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Object encapsulation network content address data more reference help configuration good Zhongtong location information interest customer client partner attribute Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Microsoft macOS Shulou Information Docker