笔记1:一个Java传输数据(json)的简单例子

这篇笔记介绍了一个简单的Java应用,该应用通过HTTP监听并返回预设的JSON内容。使用现代开发工具,编程变得更为便捷。文章包含了POM配置、服务器端的JsonHttpHandler和JsonServerStarter类的说明,以及客户端调用的JsonClient部分。

很久没编程,现在开发工具太智能了。

用Java编写一个简单的监听、调用程序。

通过浏览器调用http://localhost:8019/server ,即可调出预设的json内容。

原创

POM

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>demoMaven</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>demoMaven</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.13.3</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.13.3</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.9.4</version>
    </dependency>
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.2</version>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.4</version>
      <classifier>jdk15</classifier>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.4</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>8</source>
          <target>8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

服务器端:(1)JsonHttpHandler.java

package com.hlb.httpserver;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import net.sf.json.JSONArray; //不可导错
import net.sf.json.JSONObject;

import java.io.OutputStream;

/**
 * 处理/server路径请求的处理器类
 */
public class JsonHttpHandler implements HttpHandler {

    @Override
    public void handle(HttpExchange httpExchange) {
        try {

            StringBuilder responseText = new StringBuilder();
            String parameter = "{ \"success\" : 1,  " +
                    "  \"orderId\" : \"A0101001\",  " +
                    "  \"custRelation\" : {" +
                    "  \"total\":\"2\",  " +
                    "   \"data\" : [ {  " +
                    "    \"relationName\" : \"A镇1厂\",  " +
                    "    \"amt\" : \"12000\",  " +
                    "    \"createDate\" : \"20220101\"" +
                    "   },\n" +
                    "   {\"relationName\" : \"A镇2厂\",  " +
                    "    \"amt\" : \"22000\",  \n" +
                    "    \"createDate\" : \"20201201\"" +
                    "   }]}" +
                    "}";
            responseText.append(parameter);
            handleResponseJs(httpExchange, responseText.toString());
            //后台输出日志
            logJson(parameter);
            //删除等
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 处理响应
     * @param httpExchange
     * @param responsetext
     * @throws Exception
     */

    private void handleResponseJs(HttpExchange httpExchange, String responsetext) throws Exception {
        //生成html
        StringBuilder responseContent = new StringBuilder();
        responseContent.append(responsetext);
        String responseContentStr = responseContent.toString();
        byte[] responseContentByte = responseContentStr.getBytes("utf-8");

        //设置响应头,必须在sendResponseHeaders方法之前设置!
        //httpExchange.getResponseHeaders().add("Content-Type:", "text/html;charset=utf-8");

        //设置响应码和响应体长度,必须在getResponseBody方法之前调用!
        httpExchange.sendResponseHeaders(88, responseContentByte.length);

        OutputStream out = httpExchange.getResponseBody();
        out.write(responseContentByte);
        out.flush();
        out.close();
    }


    public void logJson(String aa){
        ///输出日志
        JSONObject jsonObject =JSONObject.fromObject(aa);
        System.out.println("success:"+jsonObject.get("success"));
        System.out.println("orderId:"+jsonObject.get("orderId"));
        System.out.println("Total custRelation:"+jsonObject.getJSONObject("custRelation").get("total"));
        JSONObject custRelation = jsonObject.getJSONObject("custRelation");
        JSONArray jsonArray = custRelation.getJSONArray("data");
        JSONObject row = null;
        for (int i = 0; i < jsonArray.size(); i++) {
            row = jsonArray.getJSONObject(i);
            System.out.println("relationName:"+row.get("relationName"));
            System.out.println("amt:"+row.get("amt"));
            System.out.println("createDate:"+row.get("createDate"));
        }

    }
}

(2)JsonServerStarter

package com.hlb.httpserver;

import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

public class JsonServerStarter {
    public static void main(String[] args) throws IOException {
        //创建一个HttpServer实例,并绑定到指定的IP地址和端口号
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(8019), 0);

        //创建一个HttpContext,将路径为/myserver请求映射到MyHttpHandler处理器
        httpServer.createContext("/server", new JsonHttpHandler());

        //设置服务器的线程池对象
        httpServer.setExecutor(Executors.newFixedThreadPool(10));

        //启动服务器
        httpServer.start();
    }

}

客户端调用

JsonClient

package com.hlb.httpClient;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class JsonClient {

    /**
     * 调用对方接口方法
     *
     * @param path 对方或第三方提供的路径
     * @param data
     */
    public void getUrl(String path, String data) {
        try {
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");//默认GET
            // 如果只是发送GET方式请求,使用connet方法建立和远程资源之间的实际连接即可;
            conn.connect();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            String jsonStr = "";
            while ((str = br.readLine()) != null) {
                str = new String(str.getBytes(), "UTF-8");
                jsonStr = jsonStr + str;
            }
            //jsonStr = jsonStr.replace("<html>", "").replace("<body>","").replace("</html>","").replace("</body>","");
            System.out.println(jsonStr);
            logJson(jsonStr);
            //关闭流
            is.close();
            //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
            System.out.println("====");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void logJson(String aa) {
        ///输出日志
        JSONObject jsonObject = JSONObject.fromObject(aa);
        System.out.println("success:" + jsonObject.get("success"));
        System.out.println("orderId:" + jsonObject.get("orderId"));
        System.out.println("Total custRelation:" + jsonObject.getJSONObject("custRelation").get("total"));
        JSONObject custRelation = jsonObject.getJSONObject("custRelation");
        JSONArray jsonArray = custRelation.getJSONArray("data");
        JSONObject row = null;
        for (int i = 0; i < jsonArray.size(); i++) {
            row = jsonArray.getJSONObject(i);
            System.out.println("relationName:" + row.get("relationName"));
            System.out.println("amt:" + row.get("amt"));
            System.out.println("createDate:" + row.get("createDate"));
        }
    }


    public static void main(String[] args) {
        JsonClient js=new JsonClient();
        js.getUrl("http://localhost:8019/server?aaa=1", "");
    }

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值