Java 之利用OkHttpClient进行简单的http请求,利用Jackson框架把json转化为java对象的实现

Posted 三尺剑

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 之利用OkHttpClient进行简单的http请求,利用Jackson框架把json转化为java对象的实现相关的知识,希望对你有一定的参考价值。

实现的业务逻辑是这样的:
通过http请求,返回一个json格式的数据,然后将json数据转化为java对象返回给调用方。
Http采用OkHttp库,json转化采用jackson库。
一.简介
1)okhttpclient
OkHttpClient官网: http://square.github.io/okhttp/
OkHttp GitHub地址:https://github.com/square/okhttp
最常用的是两个http请求是get和post,我下面的代码就只用到这两个请求。
Maven依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
2)jackson
Jackson的文档:http://wiki.fasterxml.com/JacksonInFiveMinutes
Jackson的maven依赖
<dependency>
<groupId>com.fasterxml.jackson</groupId>
<artifactId>jackson-parent</artifactId>
<version>2.8</version>
</dependency>
由于采用了javabean的方式,所以json和java类的互转变得简单。

二.代码
java类:

public  class Transaction {
  //使用了静态的内部类
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请求:

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(); // 返回的是string 类型,json的mapper可以直接处理
}

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转化:

public Transaction[] getTransaction(int skip,int limit){
String txHistoryUrl = String.format("%s%s?skip=%d&limit=%d",url,TX_HISTORY,skip,limit); //url 后边的参数是业务规定,格式可以参考,具体可以自定义
System.out.println(txHistoryUrl);
try{
String newTx = HttpClient.httpGet(txHistoryUrl);
System.out.println(newTx);
ObjectMapper mapper = new ObjectMapper(); // 只需要一个mapper就可以实现
return mapper.readValue(newTx,Transaction[].class);
}catch (IOException e){
e.printStackTrace();
}
return null;
}
json数据如下:
[{"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"}]}]

三.问题解决
Json错误:Can not deserialize instance of xx out of START_ARRAY token
Server
这个可能是后台返回的是数组类型的json,所以transaction要用数组
return mapper.readValue(newTx,Transaction[].class);
json错误:
No suitable constructor found for type [xxxx]: can not instantiate from JSON object (need to add/enable type information?) at xxx
这个需要java class中的内部类使用静态类,见transaction类中的output内部类。

后续复杂应用,再接着写。

 






















































































































































以上是关于Java 之利用OkHttpClient进行简单的http请求,利用Jackson框架把json转化为java对象的实现的主要内容,如果未能解决你的问题,请参考以下文章

Android开发之利用SQLite进行数据存储

(转)java redis使用之利用jedis实现redis消息队列

前端性能优化之利用 Chrome Dev Tools 进行页面性能分析

Java之利用openCsv导出csv文件

2019-04-15 Python之利用matplotlib和numpy的简单绘图

机器学习之利用KNN近邻算法预测数据