zoukankan      html  css  js  c++  java
  • pb协议 jdk序列化协议

    1 pb协议

    协议由序列化容量,jdk pb json kryo

    server:

    使用spring boot

    	// 将服务器容器http body序列化方式指定为pb
    		/**
    		 * protobuf 序列化
    		 */
    		@Bean
    		ProtobufHttpMessageConverter protobufHttpMessageConverter() {
    			return new ProtobufHttpMessageConverter();
    		}
    
    		/**
    		 * protobuf 反序列化
    		 */
    		@Bean
    		RestTemplate restTemplate(ProtobufHttpMessageConverter protobufHttpMessageConverter) {
    			return new RestTemplate(Collections.singletonList(protobufHttpMessageConverter));
    		}
    

    这两个bean告诉springboot,使用pb序列化

    @Controller
    @RequestMapping("/pb")
    public class PbController {
    
        @RequestMapping(value = "/test", produces = "application/x-protobuf")
        @ResponseBody
        public MyBaseProto.BaseProto getPersonProto(@RequestBody MyBaseProto.BaseProto request) {
    
            MyBaseProto.BaseProto.Builder builder = MyBaseProto.BaseProto.newBuilder();
            builder.setCode(request.getCode() + 1);
            builder.setMsg(request.getMsg() + "back");
            System.out.println(request.getCode() + request.getMsg());
            return builder.build();
        }
    }
    

    client:

     java.net.URL object = new URL("http://127.0.0.1:8080/pb/test");
                HttpURLConnection con = (HttpURLConnection) object.openConnection();
                con.setDoOutput(true);
                con.setDoInput(true);
    
                // 此句必须,否则默认application/x-www-form-urlencoded;charset=UTF-8
                // */*也不行,服务器spring boot不认
                con.setRequestProperty("Content-Type", "application/x-protobuf");
    
                // 此句可省略
    //            con.setRequestProperty("Accept", "application/x-protobuf");
    
                // 此句可省略
    //            con.setRequestMethod("POST");
    
                // json协议,本文不用
                /**
                JSONObject data = new JSONObject();
                JSONObject tel = new JSONObject();
                tel.put("nationcode", nationCode);
                String phone = phoneNumber;
                tel.put("phone", phone);
                data.put("type", "0");
                data.put("msg", content);
                String sig = stringMD5(APPKEY.concat(phone));
                data.put("sig", sig);
                data.put("tel", tel);
                 */
    
                // pb协议,自定义http协议
                MyBaseProto.BaseProto.Builder builder = MyBaseProto.BaseProto.newBuilder();
                builder.setCode(1);
                builder.setMsg("test");
                byte [] pb = builder.build().toByteArray();
                OutputStream wr = con.getOutputStream();
                wr.write(pb);
                wr.flush();
    
                // 显示 POST 请求返回的内容
                StringBuilder sb = new StringBuilder();
                int HttpResult = con.getResponseCode();
                if (HttpResult == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = con.getInputStream();
                    ByteArrayOutputStream result = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = inputStream.read(buffer)) != -1) {
                        result.write(buffer, 0, length);
                    }
                    MyBaseProto.BaseProto baseProto = MyBaseProto.BaseProto.parseFrom(result.toByteArray());
                    System.out.println(baseProto.getCode() + baseProto.getMsg());
    
                } else {
                    System.out.println("http error");
                }
    

    参考:https://blog.csdn.net/u013219624/article/details/83152806

    2 jdk序列化

    server:使用jetty

    import java.io.*;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.eclipse.jetty.server.Server;
    import org.eclipse.jetty.servlet.ServletContextHandler;
    import org.eclipse.jetty.servlet.ServletHolder;
    import serial.MyBaseBean;
    
    public class EmbeddingJettyWithServlet {
    
        public static void main(String[] args) throws Exception {
    
            Server server = new Server(8080);
    
            ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
            context.setContextPath("/jdk");
            server.setHandler(context);
    
            context.addServlet(new ServletHolder(new HelloServlet()), "/test");
            server.start();
    
        }
    
        public static class HelloServlet extends HttpServlet {
    
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
               dohandle(req, resp);
            }
    
            @Override
            protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                dohandle(req, resp);
            }
    
            private void dohandle(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
                MyBaseBean myBaseBean = null;
                try {
                    InputStream inputStream = req.getInputStream();
                    ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
    
                    try {
                        myBaseBean = (MyBaseBean)objectInputStream.readObject();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
    
                    System.out.println("get--" + myBaseBean.getCode() + myBaseBean.getMsg());
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
                if(myBaseBean == null)
                    myBaseBean = new MyBaseBean();
    
                myBaseBean.setCode(myBaseBean.getCode() + 1);
                myBaseBean.setMsg(myBaseBean.getMsg() + "back");
    
                resp.setContentType("text/html");
                resp.setStatus(HttpServletResponse.SC_OK);
    
    
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
                objectOutputStream.writeObject(myBaseBean);
    
                OutputStream outputStream = resp.getOutputStream();
                outputStream.write(byteArrayOutputStream.toByteArray());
                outputStream.flush();
            }
        }
    

    浏览器访问:http://localhost:8080/jdk/test

    �srserial.MyBaseBean襹s臥H<�IcodeLmsgtLjava/lang/String;xpttestback

    client:

    URL object = new URL("http://127.0.0.1:8080/jdk/test");
                HttpURLConnection con = (HttpURLConnection) object.openConnection();
                con.setDoOutput(true);
                con.setDoInput(true);
    
    
                // jdk协议,自定义http协议
                MyBaseBean myBaseBean = new MyBaseBean();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
                objectOutputStream.writeObject(myBaseBean);
                objectOutputStream.flush();
                byte [] pb = byteArrayOutputStream.toByteArray();
                OutputStream wr = con.getOutputStream();
                wr.write(pb);
                wr.flush();
    
                // 显示 POST 请求返回的内容
                StringBuilder sb = new StringBuilder();
                int HttpResult = con.getResponseCode();
                if (HttpResult == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = con.getInputStream();
                    ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
                    MyBaseBean myBaseBean1 = (MyBaseBean)objectInputStream.readObject();
                    System.out.println(myBaseBean1.getCode() + myBaseBean1.getMsg());
    
                } else {
                    System.out.println("http error");
                }
    

    参考:http://www.mamicode.com/info-detail-2224013.html 

  • 相关阅读:
    时间控件的操作
    Appium环境搭建
    测试常用英文词汇
    自动化测试中一段代码对应多个用例
    Linux常见命令
    元素的操作的简谈
    eclipse代码编辑界面代码块收缩的实现
    关键字驱动和数据驱动
    uni-app中如何判断浏览器内核
    JS实现 图片放大镜功能
  • 原文地址:https://www.cnblogs.com/silyvin/p/11892748.html
Copyright © 2011-2022 走看看