资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

HttpClient、FastJson将json转换为JavaBean

HttpClient

一、HttpClient简介

    HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
    HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。

创新互联公司2013年开创至今,是专业互联网技术服务公司,拥有项目成都网站制作、成都网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元胶州做网站,已为上家服务,为胶州各地企业和个人服务,联系电话:18980820575

二、FastJson

1、FastJson简介

Fastjson 是一个 Java 库,可以将 Java 对象转换为 JSON 格式,当然它也可以将 JSON 字符串转换为 Java 对象。

Fastjson 可以操作任何 Java 对象,即使是一些预先存在的没有源码的对象。

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

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

FastJson特性

提供服务器端、安卓客户端两种解析工具,性能表现较好。

提供了 toJSONString() 和 parseObject() 方法来将 Java 对象与 JSON 相互转换。调用toJSONString方 法即可将对象转换成 JSON 字符串,parseObject 方法则反过来将 JSON 字符串转换成对象。

允许转换预先存在的无法修改的对象(只有class、无源代码)。

Java泛型的广泛支持。

允许对象的自定义表示、允许自定义序列化类。

支持任意复杂对象(具有深厚的继承层次和广泛使用的泛型类型)。

例子

1、GetData.java:使用httpclient接收数据、再用fastJson将json数据解析为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();

        //创建get请求实例
        //HttpGet get = new HttpGet("http://www.baidu.com");
        HttpGet get = new HttpGet("http://localhost:7333/a");
        System.out.println("请求的uri为:"+get.getURI());

        try {
            // 客户端执行get请求 返回响应实体
            HttpResponse response = client.execute(get);

            //获取请求状态行
            System.out.println("请求状态行为:"+response.getStatusLine());

            //获取所有的请求头
            Header[] headers=response.getAllHeaders();

            for (Header header :headers){
            //遍历获取所有请求头的名称和值
            System.out.println(header.getName()+" :--: "+header.getValue());
            }
            System.out.println("-----------------------------------------------");
            //获取响应的实体
            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("内容长度为:"+entity.getContentLength());
        }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //释放连接
            client.getConnectionManager().shutdown();
        }
    }
}

2、http://localhost:7333/a返回的json数据

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

3、User.java实体类

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、

输出结果:

请求的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
请求状态行为: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
=================================
内容长度为:-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

网站名称:HttpClient、FastJson将json转换为JavaBean
分享地址:http://cdkjz.cn/article/ggghec.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220