pb sequence of protocol agreement jdk

1 pb agreement

Agreement by the sequence of capacity, jdk pb json kryo

server:

Use spring boot

	// http body vessel server serialization designated Pb 
		/ ** 
		 * Protobuf serialization 
		 * / 
		@Bean 
		ProtobufHttpMessageConverter protobufHttpMessageConverter () { 
			return new new ProtobufHttpMessageConverter (); 
		} 

		/ ** 
		 * Protobuf deserialized 
		 * / 
		@Bean 
		RestTemplate RestTemplate (protobufHttpMessageConverter protobufHttpMessageConverter) { 
			return new new RestTemplate (Collections.singletonList (protobufHttpMessageConverter)); 
		}

 

The two bean told springboot, using a sequence of 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:

Object = new new the java.net.URL ( "http://127.0.0.1:8080/pb/test") the URL; 
            the HttpURLConnection = CON (the HttpURLConnection) object.openConnection (); 
            con.setDoOutput (to true); 
            con.setDoInput ( to true); 

            // sentence must, otherwise default the Application / the X--the WWW-form-urlencoded; charset = UTF-8 
            // * / * does not work, spring boot server does not recognize 
            con.setRequestProperty ( "Content-Type", " file application / X-Protobuf "); 

            // sentence may be omitted 
// con.setRequestProperty (" the Accept "," file application / X-Protobuf "); 

            // sentence may be omitted 
// con.setRequestMethod (" POST ");

            // json protocol, herein do 
            / ** 
            the JSONObject the JSONObject new new Data = ();
            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");
            }

 

Reference: https: //blog.csdn.net/u013219624/article/details/83152806

 

2 jdk serialization

server: Use 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();
        }
    }

 

Browser to access: 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");
            }

 

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

Guess you like

Origin www.cnblogs.com/silyvin/p/11892748.html