Java uses okhttpclient to make simple HTTP requests, using the Jackson Framework to transform JSON into Java object implementations

Source: Internet
Author: User

The business logic that is implemented is this:
A JSON-formatted data is returned through an HTTP request, and the JSON data is then converted to a Java object and returned to the caller.
HTTP uses the Okhttp library, and JSON transforms using the Jackson Library.
I. INTRODUCTION
1) okhttpclient
Okhttpclient Official website: http://square.github.io/okhttp/
OkHttp GitHub Address: https://github.com/square/okhttp
The most common is that two HTTP requests are get and post, and the following code only uses these two requests.
Maven dependencies:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
2) Jackson
Jackson's Documentation: Http://wiki.fasterxml.com/JacksonInFiveMinutes
Jackson's Maven dependency
<dependency>
<groupId>com.fasterxml.jackson</groupId>
<artifactId>jackson-parent</artifactId>
<version>2.8</version>
</dependency>
Because of the javabean approach, the mutual transfer of JSON and Java classes becomes simple.

Two Code
Java class:

public class Transaction {
Static internal classes are used
Public static Class output{
String address;
Long amount;

Public String getaddress () {
return address;
}

Public long Getamount () {
return amount;
}

public void setaddress (String address) {
this.address = address;
}

public void Setamount (long amount) {
This.amount = amount;
}

@Override
Public String toString () {
Return "output{" +
"address=" + address + ' \ ' +
", amount=" + Amount +
‘}‘;
}
}

Private String Txid;
Private String action;
Private long amount;
Private long fees;
Private long time;
private int confirmations;
private list<output> outputs;

public void Settxid (String txid) {
This.txid = Txid;
}

public void Setaction (String action) {
This.action = action;
}

public void Setamount (long amount) {
This.amount = amount;
}

public void setfees (long fees) {
this.fees = fees;
}

public void SetTime (long time) {
This.time = time;
}

public void setconfirmations (int confirmations) {
This.confirmations = confirmations;
}

Public String Gettxid () {
return TXID;
}

public void setoutputs (list<output> outputs) {
This.outputs = outputs;
}

@Override
Public String toString () {
Return "transaction{" +
"Txid=" + txid + ' + ' +
", action= '" + action + "\" +
", amount=" + Amount +
", fees=" + Fees +
", time=" + Time +
", confirmations=" + confirmations +
", outputs=" + Outputs +
‘}‘;
}
}

HTTP request:

public class HttpClient {
public static final MediaType JSON = Mediatype.parse ("Application/json;charset=utf-8");

public static string HttpGet (string url) throws IOException {
Okhttpclient httpClient = new Okhttpclient ();
Request Request = new Request.builder ()
. URL (URL)
. build ();
Response Response = httpclient.newcall (Request). Execute ();
Return Response.body (). String (); The string type is returned, and the JSON mapper can be processed directly
}

public static string HttpPost (string URL, string json) throws IOException {
Okhttpclient httpClient = new Okhttpclient ();
Requestbody requestbody = requestbody.create (JSON, JSON);
Request Request = new Request.builder ()
. URL (URL)
. Post (Requestbody)
. build ();
Response Response = httpclient.newcall (Request). Execute ();
Return Response.body (). String ();
}

JSON conversion:

Public transaction[] gettransaction (int skip,int limit) {
String Txhistoryurl = String.Format ("%s%s?skip=%d&limit=%d", url,tx_history,skip,limit); The parameters behind the URL are business rules, the format can be referenced, specific can be customized
System.out.println (Txhistoryurl);
try{
String newtx = Httpclient.httpget (Txhistoryurl);
System.out.println (NEWTX);
Objectmapper mapper = new Objectmapper (); It takes only one mapper to achieve
Return Mapper.readvalue (Newtx,transaction[].class);
}catch (IOException e) {
E.printstacktrace ();
}
return null;
}
The JSON data is as follows:
[{"Txid": "ad416e1b4b8b807b4a0946affb17cf253c1af7a7e6c6a9e21fac2e93b2c88746", "Action": "Received", "Amount": 10000 , "fees": 3800, "Time": 1486111663, "confirmations": 179, "outputs": [{"Amount": 10000, "Address": " 2mxdyd4idpv8lqynp4aq4qexrhtckqnk8zk "}]},{" Txid ":" 2dadf7b391935af15f5f70e775ed5d7a03d629db4bdde1cd93e31b8311db4949 "," Action ":" Received "," Amount ": 1000000," fees " : 4416, "Time": 1485241194, "confirmations": 1721, "outputs": [{"Amount": 1000000, "Address": " 2mxdyd4idpv8lqynp4aq4qexrhtckqnk8zk "}]}]

Three Problem solving
JSON error: Can not deserialize instance of XX out of Start_array tokens
Server
This may be the back of the background is the array type of JSON, so transaction to use the array
Return Mapper.readvalue (Newtx,transaction[].class);
JSON error:
No suitable constructor found for type [XXXX]: Can not instantiate from JSON object (need to add/enable type information?) at XXX
This requires that the inner class in Java class Use static classes, see output inner classes in the transaction class.

Follow the complex application, then write again.

Java uses okhttpclient to make simple HTTP requests, using the Jackson Framework to transform JSON into Java object implementations

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.