zoukankan      html  css  js  c++  java
  • MQTT的学习研究(七)基于HTTP POST MQTT 发布消息服务端使用

    参阅官方文档

    http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/topic/com.ibm.mq.csqzau.doc/ts21220_.htm

               HTTP POST puts a message to a queue, or a publication to a topic. The HTTPPOST Java sample is an example an HTTP POST request of a message to a queue. Instead of using Java, you could create an HTTPPOST request using a browser form, or an AJAX toolkit instead.

    Figure 1 shows an HTTP request to put a message on a queue called myQueue. This request contains the HTTP header x-msg-correlId to set the correlation ID of the WebSphere MQ message.

    Figure 1. Example of an HTTP POST request to a queue
    POST /msg/queue/myQueue/ HTTP/1.1
    Host: www.example.org
    Content-Type: text/plain
    x-msg-correlID: 1234567890
    Content-Length: 50
    
    Here's my message body that will appear on the queue.

    Figure 2 shows the response sent back to the client. There is no response content.

    Figure 2. Example of an HTTP POST response
    HTTP/1.1 200 OK
    Date: Wed, 2 Jan 2007 22:38:34 GMT
    Server: Apache-Coyote/1.1 WMQ-HTTP/1.1 JEE-Bridge/1.1
    Content-Length: 0

    请求的协议格式和请求的响应格式

    The HTTP POST operation puts a message on a WebSphere® MQ queue, or publishes a message to a topic.

    Syntax

    Request
    
    >>-POST-- --| Path |-- --HTTP version--CRLF--------------------->
    
       .-CRLF---------------.  .-CRLF---------------.   
       V                    |  V                    |   
    >----+----------------+-+----+----------------+-+--------------->
         '-general-header-'      '-request-header-'     
    
       .-CRLF----------------------------.        .-CRLF----.   
       V                                 |        V         |   
    >----+-----------------------------+-+--CRLF----Message-+------><
         '-| entity header (Request) |-'                        
    
    Path
    
    |--/--contextRoot--/-------------------------------------------->
    
    >--msg/--+-queue/--queueName--+-------------+-+--/--------------|
             |                    '-@--qMgrName-' |      
             '-topic/--topicName------------------'      
    
    entity-header (Request)
    
    |--+----------------------------------------------+-------------|
       +-standard entity-header-- --entity-value------+   
       +-x-msg-class-- --message type-----------------+   
       +-x-msg-correlId-- --correlation ID------------+   
       +-x-msg-encoding-- --encoding type-------------+   
       +-x-msg-expiry-- --duration--------------------+   
       +-x-msg-format-- --message format--------------+   
       +-x-msg-msgId-- --message ID-------------------+   
       +-x-msg-persistence-- --persistence------------+   
       +-x-msg-priority-- --priority class------------+   
       +-x-msg-replyTo-- --reply-to queue-------------+   
       +-x-msg-require-headers-- --entity header name-+   
       '-x-msg-usr-- --user properties----------------'   
    
    
    Note:
    1. If a question mark (?) is used it must be substituted with %3f. For example, orange?topic should be specified as orange%3ftopic.
    2. @qMgrName is only valid on an HTTP POST
    Response
    
    >>-HTTP version-- --HTTP Status-Code-- --HTTP Reason-Phrase--CRLF-->
    
       .-CRLF---------------.  .-CRLF----------------.   
       V                    |  V                     |   
    >----+----------------+-+----+-----------------+-+-------------->
         '-general-header-'      '-response-header-'     
    
       .-CRLF-----------------------------.   
       V                                  |   
    >----+------------------------------+-+------------------------><
         '-| entity-header (Response) |-'     
    
    entity-header (Response)
    
    |--+-----------------------------------------+------------------|
       +-standard entity-header-- --entity-value-+   
       +-x-msg-class-- --message type------------+   
       +-x-msg-correlId-- --correlation ID-------+   
       +-x-msg-encoding-- --encoding type--------+   
       +-x-msg-expiry-- --duration---------------+   
       +-x-msg-format-- --message format---------+   
       +-x-msg-msgId-- --message ID--------------+   
       +-x-msg-persistence-- --persistence-------+   
       +-x-msg-priority-- --priority class-------+   
       +-x-msg-replyTo-- --reply-to queue--------+   
       +-x-msg-timestamp-- --HTTP-date-----------+   
       '-x-msg-usr-- --user properties-----------'   
    
    
    HTTP POST方式实现如下:
    Java代码  收藏代码
    1. package com.etrip.mqttv3.http;  
    2.   
    3.   
    4.   
    5. /** 
    6.  * This sample shows how to post a message. It has the same behaviour as the 
    7.  * amqsput command in that it will read in lines from the command line and put 
    8.  * them to the queue. It will put non-persistent String messages on to the queue 
    9.  * with UNLIMITED expiry and LOW (0) priority. The program is terminated by 
    10.  * either EOF being put into the entry line (^Z on windows) or a blank line. 
    11.  * usage: java HTTPPOST <Queue (default=SYSTEM.DEFAULT.LOCAL.QUEUE)> <host:port 
    12.  * (default localhost:8080> <context-root (the MQ Bridge for HTTP's 
    13.  * context-root)> 
    14.  */  
    15.   
    16. import java.io.BufferedReader;  
    17. import java.io.BufferedWriter;  
    18. import java.io.IOException;  
    19. import java.io.InputStreamReader;  
    20. import java.io.OutputStream;  
    21. import java.io.OutputStreamWriter;  
    22. import java.net.HttpURLConnection;  
    23. import java.net.MalformedURLException;  
    24. import java.net.URL;  
    25. /** 
    26.  *  
    27.  * 采用HTTP POST发布相关的消息  
    28.  *     The HTTP POST operation puts a message on a WebSphere® MQ queue, or publishes 
    29.  *  a message to a topic.  
    30.  *   
    31.  *  发布消息到主题或者队列的路径: 
    32.  *   
    33.  *   
    34.  *   
    35.  *   
    36.  *  
    37.  * @author longgangbai 
    38.  */  
    39. public class HTTPPOST  
    40. {  
    41.    private static final String DEFAULT_HOST = "localhost";  
    42.    private static final String DEFAULT_PORT = "8080";  
    43.    private static final String DEFAULT_QUEUE = "SYSTEM.DEFAULT.LOCAL.QUEUE";  
    44.   
    45.    private static final String DEFAULT_CONTEXT_ROOT = "mq";  
    46.   
    47.    private static final String CRLF = " ";  
    48.   
    49.    public static int MALFORMED_URL_EXCEPTION_RC = -1;  
    50.   
    51.    public static int END_IOEXCEPTION_RC = -2;  
    52.   
    53.    /** 
    54.     * 构建发布主题队列路径 
    55.     *  
    56.     * @param host 
    57.     * @param port 
    58.     * @param context 
    59.     * @param queueName 
    60.     */  
    61.     private static String getPublishQueueURL(String host, String port,  
    62.             String context, String queueName) {  
    63.         StringBuffer urlString =new StringBuffer("http://");  
    64.            if(StringUtils.isEmtry(host)){  
    65.                host=DEFAULT_HOST;  
    66.            }  
    67.              
    68.            if(StringUtils.isEmtry(port)){  
    69.                port=DEFAULT_PORT;  
    70.            }  
    71.            urlString.append(host).append(":").append(port);  
    72.            if(StringUtils.isEmtry(context)){  
    73.                context=DEFAULT_CONTEXT_ROOT;  
    74.            }  
    75.            urlString.append("/");  
    76.            urlString.append(context);  
    77.            urlString.append("/msg/queue/");  
    78.            if(StringUtils.isEmtry(queueName)){  
    79.            }  
    80.            queueName=DEFAULT_QUEUE;  
    81.            urlString.append(queueName);  
    82.            System.out.println("urlString="+urlString);  
    83.            return urlString.toString();  
    84.     }  
    85.      
    86.     /** 
    87.      *   
    88.      * @param host 
    89.      * @param port 
    90.      * @param context 
    91.      * @param queueName 
    92.      * @param message 
    93.      * @return 
    94.      * @throws MalformedURLException 
    95.      */  
    96.        public static boolean publishTopic(String host,String port,String context,String queueName,String message ){  
    97.            boolean response = true;     
    98.            HttpURLConnection connection=null;  
    99.            try {  
    100.                     String publishURL=getPublishQueueURL(host, port, context, queueName);  
    101.                       URL url=new URL(publishURL);  
    102.                       connection = (HttpURLConnection) url.openConnection();  
    103.   
    104.                       /* Build the headers */  
    105.                       // the verb first  
    106.                       connection.setRequestMethod("POST");  
    107.   
    108.                       // Content type is a string message  
    109.                       connection.setRequestProperty("content-type", "text/plain");  
    110.   
    111.                       // set the message priority to low  
    112.                       connection.setRequestProperty("x-msg-priority", "LOW");  
    113.   
    114.                       // Ensure we can get the output stream from the connection  
    115.                       connection.setDoOutput(true);  
    116.   
    117.                       OutputStream outputStream = connection.getOutputStream();  
    118.                       // wrapper the outputstream in a writer  
    119.                       BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(  
    120.                             outputStream));  
    121.   
    122.                       // Now write the actual content.  
    123.                       // Make sure the CRLF is there in case some HTTP servers don't understand  
    124.                       // that it's the end of the message  
    125.                       writer.write(message + CRLF + CRLF);  
    126.                       writer.flush();  
    127.   
    128.                       // now actually send the message  
    129.                       connection.connect();  
    130.                        
    131.                       // check the response for errors  
    132.                       int responseCode = connection.getResponseCode();  
    133.                     if (responseCode != 200)  
    134.                       {  
    135.                            
    136.                           String responseMessage =connection.getResponseMessage();  
    137.                           System.out.println("responsere sponseCode "+responseCode+" response request ="+responseMessage);  
    138.                           System.out.println("responsere context ");  
    139.                          BufferedReader reader = new BufferedReader(new InputStreamReader(  
    140.                                  connection.getErrorStream()));  
    141.                            String line = null;  
    142.                            while ((line = reader.readLine()) != null)  
    143.                            {  
    144.                               System.out.println(line);  
    145.                            }  
    146.                          connection.disconnect();  
    147.                          response = false;  
    148.                       }else{  
    149.                           //获取相应的消息头信息  
    150.                           String responseQueueName=connection.getHeaderField("x-msg-replyTo");  
    151.                           System.out.println("responseQueueName="+responseQueueName);  
    152.                           System.out.println("response successful context :"+connection.getResponseMessage());  
    153.                       }  
    154.             } catch (MalformedURLException e) {  
    155.                 response = false;  
    156.                 e.printStackTrace();  
    157.                 // TODO: handle exception  
    158.             } catch (IOException e) {  
    159.                  response = false;  
    160.                 // TODO Auto-generated catch block  
    161.                 e.printStackTrace();  
    162.             }finally{  
    163.                 connection.disconnect();  
    164.             }  
    165.             return response;  
    166.        }  
    167.          
    168.        public static void main(String[] args) {  
    169.            HTTPPOST.publishTopic("192.168.208.46", "8080", "mq", "java_lover", "this is a message ");  
    170.        }  
    171. }  
     
  • 相关阅读:
    静态连接库
    03数据的增删改查
    02MySQL中的数据类型
    01MySQL的 库、表初步认识
    Python 函数
    Linux系统目录结构
    Linux系统启动过程
    第三章 Web页面建设
    《第二章:深入了解超文本》
    《HTML与CSS 第一章 认识HTML》读书笔记
  • 原文地址:https://www.cnblogs.com/yudar/p/4613745.html
Copyright © 2011-2022 走看看