溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

HttpClient、FastJson將json轉(zhuǎn)換為JavaBean

發(fā)布時(shí)間:2020-07-15 20:05:32 來源:網(wǎng)絡(luò) 閱讀:1295 作者:Qiu_CJ 欄目:軟件技術(shù)

HttpClient

一、HttpClient簡介

????HttpClient 是Apache Jakarta Common 下的子項(xiàng)目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。
????HTTP 協(xié)議可能是現(xiàn)在 Internet 上使用得最多、最重要的協(xié)議了,越來越多的 Java 應(yīng)用程序需要直接通過 HTTP 協(xié)議來訪問網(wǎng)絡(luò)資源。雖然在 JDK 的 java net包中已經(jīng)提供了訪問 HTTP 協(xié)議的基本功能,但是對(duì)于大部分應(yīng)用程序來說,JDK 庫本身提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common 下的子項(xiàng)目,用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。HttpClient 已經(jīng)應(yīng)用在很多的項(xiàng)目中,比如 Apache Jakarta 上很著名的另外兩個(gè)開源項(xiàng)目 Cactus 和 HTMLUnit 都使用了 HttpClient。

二、FastJson

1、FastJson簡介

Fastjson 是一個(gè) Java 庫,可以將 Java 對(duì)象轉(zhuǎn)換為 JSON 格式,當(dāng)然它也可以將 JSON 字符串轉(zhuǎn)換為 Java 對(duì)象。

Fastjson 可以操作任何 Java 對(duì)象,即使是一些預(yù)先存在的沒有源碼的對(duì)象。

Fastjson 源碼地址:https://github.com/alibaba/fastjson

Fastjson 中文 Wiki:https://github.com/alibaba/fastjson/wiki/Quick-Start-CN

FastJson特性

提供服務(wù)器端、安卓客戶端兩種解析工具,性能表現(xiàn)較好。

提供了 toJSONString() 和 parseObject() 方法來將 Java 對(duì)象與 JSON 相互轉(zhuǎn)換。調(diào)用toJSONString方 法即可將對(duì)象轉(zhuǎn)換成 JSON 字符串,parseObject 方法則反過來將 JSON 字符串轉(zhuǎn)換成對(duì)象。

允許轉(zhuǎn)換預(yù)先存在的無法修改的對(duì)象(只有class、無源代碼)。

Java泛型的廣泛支持。

允許對(duì)象的自定義表示、允許自定義序列化類。

支持任意復(fù)雜對(duì)象(具有深厚的繼承層次和廣泛使用的泛型類型)。

例子

1、GetData.java:使用httpclient接收數(shù)據(jù)、再用fastJson將json數(shù)據(jù)解析為JavaBean。

package com.get_data.get;

import java.io.IOException;
import com.alibaba.fastjson.JSON;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class GetData {

    public static void main(String[] args) {

        HttpClient client = new DefaultHttpClient();

        //創(chuàng)建get請(qǐng)求實(shí)例
        //HttpGet get = new HttpGet("http://www.baidu.com");
        HttpGet get = new HttpGet("http://localhost:7333/a");
        System.out.println("請(qǐng)求的uri為:"+get.getURI());

        try {
            // 客戶端執(zhí)行g(shù)et請(qǐng)求 返回響應(yīng)實(shí)體
            HttpResponse response = client.execute(get);

            //獲取請(qǐng)求狀態(tài)行
            System.out.println("請(qǐng)求狀態(tài)行為:"+response.getStatusLine());

            //獲取所有的請(qǐng)求頭
            Header[] headers=response.getAllHeaders();

            for (Header header :headers){
            //遍歷獲取所有請(qǐng)求頭的名稱和值
            System.out.println(header.getName()+" :--: "+header.getValue());
            }
            System.out.println("-----------------------------------------------");
            //獲取響應(yīng)的實(shí)體
            HttpEntity entity =response.getEntity();

            if (entity!=null){
            String str=EntityUtils.toString(entity,"UTF-8");
            System.out.println("entity:"+str);
            System.out.println("獲取到的json為:"+str);

            User newUser = JSON.parseObject(str, User.class);
            System.out.println("User: "+newUser);
            System.out.println("newUser.getAddress(): "+newUser.getAddress());

            //System.out.println(EntityUtils.toString(entity,"UTF-8"));
            System.out.println("=================================");
            System.out.println("內(nèi)容長度為:"+entity.getContentLength());
        }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //釋放連接
            client.getConnectionManager().shutdown();
        }
    }
}

2、http://localhost:7333/a返回的json數(shù)據(jù)

{
    "name":"James",
    "age":18,
    "address":"chongqing"
}

3、User.java實(shí)體類

public class User {
    private String name;
    private int age;
    private String sex;

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
}

4、

輸出結(jié)果:

請(qǐng)求的uri為:http://localhost:7333/a
14:31:04.341 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Get connection for route {}->http://localhost:7333
14:31:04.387 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connecting to localhost:7333
14:31:04.403 [main] DEBUG org.apache.http.client.protocol.RequestAddCookies - CookieSpec selected: default
14:31:04.403 [main] DEBUG org.apache.http.client.protocol.RequestAuthCache - Auth cache not set in the context
14:31:04.403 [main] DEBUG org.apache.http.client.protocol.RequestTargetAuthentication - Target auth state: UNCHALLENGED
14:31:04.403 [main] DEBUG org.apache.http.client.protocol.RequestProxyAuthentication - Proxy auth state: UNCHALLENGED
14:31:04.403 [main] DEBUG org.apache.http.impl.client.DefaultHttpClient - Attempt 1 to execute request
14:31:04.403 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Sending request: GET /a HTTP/1.1
14:31:04.403 [main] DEBUG org.apache.http.wire -  >> "GET /a HTTP/1.1[\r][\n]"
14:31:04.403 [main] DEBUG org.apache.http.wire -  >> "Host: localhost:7333[\r][\n]"
14:31:04.403 [main] DEBUG org.apache.http.wire -  >> "Connection: Keep-Alive[\r][\n]"
14:31:04.403 [main] DEBUG org.apache.http.wire -  >> "User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_161)[\r][\n]"
14:31:04.403 [main] DEBUG org.apache.http.wire -  >> "[\r][\n]"
14:31:04.403 [main] DEBUG org.apache.http.headers - >> GET /a HTTP/1.1
14:31:04.403 [main] DEBUG org.apache.http.headers - >> Host: localhost:7333
14:31:04.403 [main] DEBUG org.apache.http.headers - >> Connection: Keep-Alive
14:31:04.403 [main] DEBUG org.apache.http.headers - >> User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_161)
14:31:04.419 [main] DEBUG org.apache.http.wire -  << "HTTP/1.1 200 [\r][\n]"
14:31:04.434 [main] DEBUG org.apache.http.wire -  << "Content-Type: application/json;charset=UTF-8[\r][\n]"
14:31:04.434 [main] DEBUG org.apache.http.wire -  << "Transfer-Encoding: chunked[\r][\n]"
14:31:04.434 [main] DEBUG org.apache.http.wire -  << "Date: Tue, 01 Jan 2019 06:31:04 GMT[\r][\n]"
14:31:04.434 [main] DEBUG org.apache.http.wire -  << "[\r][\n]"
14:31:04.434 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Receiving response: HTTP/1.1 200 
14:31:04.434 [main] DEBUG org.apache.http.headers - << HTTP/1.1 200 
14:31:04.434 [main] DEBUG org.apache.http.headers - << Content-Type: application/json;charset=UTF-8
14:31:04.434 [main] DEBUG org.apache.http.headers - << Transfer-Encoding: chunked
14:31:04.434 [main] DEBUG org.apache.http.headers - << Date: Tue, 01 Jan 2019 06:31:04 GMT
14:31:04.434 [main] DEBUG org.apache.http.impl.client.DefaultHttpClient - Connection can be kept alive indefinitely
請(qǐng)求狀態(tài)行為:HTTP/1.1 200 
Content-Type :--: application/json;charset=UTF-8
Transfer-Encoding :--: chunked
Date :--: Tue, 01 Jan 2019 06:31:04 GMT
-----------------------------------------------
14:31:04.450 [main] DEBUG org.apache.http.wire -  << "2f[\r][\n]"
14:31:04.450 [main] DEBUG org.apache.http.wire -  << "{"name":"James","age":18,"address":"chongqing"}"
14:31:04.450 [main] DEBUG org.apache.http.wire -  << "[\r][\n]"
14:31:04.450 [main] DEBUG org.apache.http.wire -  << "0[\r][\n]"
14:31:04.450 [main] DEBUG org.apache.http.wire -  << "[\r][\n]"
14:31:04.450 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Releasing connection org.apache.http.impl.conn.ManagedClientConnectionImpl@4d3167f4
14:31:04.450 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Connection can be kept alive indefinitely
entity:{"name":"James","age":18,"address":"chongqing"}
獲取到的json為:{"name":"James","age":18,"address":"chongqing"}
User: User{name='James', age=18, address='chongqing'}
newUser.getAddress(): chongqing
=================================
內(nèi)容長度為:-1
14:31:04.590 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Connection 0.0.0.0:64518<->127.0.0.1:7333 closed

Process finished with exit code 0
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI