• MQTT的学习研究(八)基于HTTP DELETE MQTT 订阅消息服务端使用


    HTTP DELETE 订阅主题请求协议和响应协议
    http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/topic/com.ibm.mq.csqzau.doc/ts21240_.htm

    请求响应头各个字段的含义的讲解
    http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/topic/com.ibm.mq.csqzau.doc/ts21250_.htm


    响应错误处理
    http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/topic/com.ibm.mq.csqzau.doc/ts21340_.htm

    The HTTP DELETE operation gets a message from a WebSphere® MQ queue, or retrieves a publication from a topic. The message is removed from the queue. If the publication is retained, it is not removed. A response message is sent back to the client including information about the message.

    Syntax

    Read syntax diagram
    Skip visual syntax diagram
    Request
    
    >>-+-DELETE-+-- --| Path |-- --HTTP version--CRLF--------------->
       '-GET----'                                       
    
       .-CRLF---------------.  .-CRLF---------------.   
       V                    |  V                    |   
    >----+----------------+-+----+----------------+-+--------------->
         '-general-header-'      '-request-header-'     
    
       .-CRLF----------------------------.   
       V                                 |   
    >----+-----------------------------+-+-------------------------><
         '-| Entity-header (Request) |-'     
    
    Path
    
    |--/--contextRoot--/-------------------------------------------->
    
    >--msg/--+-queue/--queueName--+-------------+-+--/--------------|
             |                    '-@--qMgrName-' |      
             '-topic/--topicName------------------'      
    
    entity-header (Request)
    
    |--+----------------------------------------------+-------------|
       +-standard entity-header-- --entity-value------+   
       +-x-msg-correlId - --correlation ID------------+   
       +-x-msg-msgId - --message ID-------------------+   
       +-x-msg-range-- --range------------------------+   
       +-x-msg-require-headers-- --entity header name-+   
       '-x-msg-wait - --wait time---------------------'   
    
    
    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
    Read syntax diagram
    Skip visual syntax diagram
    Response
    
    >>-HTTP version-- --HTTP Status-Code-- --HTTP Reason-Phrase--CRLF-->
    
       .-CRLF---------------.  .-CRLF----------------.   
       V                    |  V                     |   
    >----+----------------+-+----+-----------------+-+-------------->
         '-general-header-'      '-response-header-'     
    
       .-CRLF-----------------------------.                      
       V                                  |                      
    >----+------------------------------+-+--+---------------+-----><
         '-| Entity-header (Response) |-'    '-CRLF--Message-'   
    
    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-----------'   
    
    

    Request parameters

    PathSee URI Format.HTTP versionHTTP version; for example, HTTP/1.1general-headerSee HTTP/1.1 - 4.5 General Header Fields.request-headerSee HTTP/1.1 - 5.3 Request Header Fields. The Host field is mandatory on an HTTP/1.1 request. It is often automatically inserted by the tool you use to create a client request.entity-header (Request)See HTTP/1.1 - 7.1 Entity Header Fields. One of the entity headers listed in the Request syntax diagram.

    Response parameters

    PathSee URI Format.HTTP versionHTTP version; for example, HTTP/1.1general-headerSee HTTP/1.1 - 4.5 General Header Fields.response-headerSee HTTP/1.1 - 6.2 Response Header Fields.entity-header (Response)See HTTP/1.1 - 7.1 Entity Header Fields. One of the entity or response headers listed in the Response syntax diagram.The Content–Length is always present in a response. It is set to zero if there is no message body.MessageMessage body.

    Description

    If the HTTP DELETE request is successful, the response message contains the data retrieved from the WebSphere MQ queue. The number of bytes in the body of the message is returned in the HTTP Content-Length header. The status code for the HTTP response is set to 200 OK. If x-msg-range is specified as 0, or0-0, then the status code of the HTTP response is 204 No Content.

    If the HTTP DELETE request is unsuccessful, the response includes a WebSphere MQ bridge for HTTP error message and an HTTP status code.

    HTTP DELETE example

    HTTP DELETE gets a message from a queue and deletes the message, or retrieves and deletes a publication. The HTTPDELETE Java sample is an example an HTTP DELETE request reading a message from a queue. Instead of using Java, you could create an HTTP DELETE request using a browser form, or an AJAX toolkit instead.

    Figure 1 is an HTTP request to delete the next message on queue called myQueue. In response, the message body is returned to the client. In WebSphere MQ terms, HTTP DELETE is a destructive get.

    The request contains the HTTP request header x-msg-wait, which instructs WebSphere MQ bridge for HTTP how long to wait for a message to arrive on the queue. The request also contains the x-msg-require-headersrequest header, which specifies that the client is to receive the message correlation ID in the response.

    Figure 1. Example of an HTTP DELETE request
    DELETE /msg/queue/myQueue/ HTTP/1.1
    Host: www.example.org
    x-msg-wait: 10
    x-msg-require-headers: correlID

    Figure 2, is the response returned to the client. The correlation ID is returned to the client, as requested in x-msg-require-headers of the request.

    Figure 2. Example of an HTTP DELETE 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: 50
    Content-Type: text/plain; charset=utf-8
    x-msg-correlId: 1234567890
    
    Here's my message body that will appear on the queue.

    HTTP DELETE订阅主题信息

    Java代码  收藏代码
    1. package com.etrip.mqttv3.http;  
    2. /** 
    3.  * This sample shows how to delete a message. It has slightly enhanced function 
    4.  * of the amqsget command in that it will print out the timestamp, expiry and 
    5.  * persistence of the messages. The program continues until the queue is empty 
    6.  * or a request fails. This program can potentially take in three parameters: 
    7.  * <queueName> 
    8.  * <host:port> <context-root (the MQ Bridge for HTTP's context-root)> 
    9.  * defaults are: SYSTEM.DEFAULT.LOCAL.QUEUE localhost:8080 mq  
    10.  *  
    11.  * If there are any exceptions thrown from this program or errors returned from the server then they are  
    12.  * printed to standard output as-is. 
    13.  *    
    14.  * No more messages 
    15.  * HTTP DELETE Sample end 
    16.  */  
    17. import java.io.BufferedReader;  
    18. import java.io.IOException;  
    19. import java.io.InputStreamReader;  
    20. import java.net.HttpURLConnection;  
    21. import java.net.MalformedURLException;  
    22. import java.net.URL;  
    23. /** 
    24.  *  
    25.  * 采用HTTP DELETE方式的订阅相关的MQTT的主题的信息 
    26.  *  
    27.  * @author longgangbai 
    28.  *  
    29.  *  
    30.  */  
    31. public class HTTPDELETE  
    32. {  
    33.    private static final String DEFAULT_HOST = "localhost";  
    34.    private static final String DEFAULT_PORT = "8080";  
    35.    private static final String DEFAULT_QUEUE = "SYSTEM.DEFAULT.LOCAL.QUEUE";  
    36.   
    37.    private static final String DEFAULT_CONTEXT_ROOT = "mq";  
    38.   
    39.    public static String newline = System.getProperty("line.separator");  
    40.   
    41.    private static final String MESSAGE_BOUNDARY = "_________________________________________________________________________________________";  
    42.   
    43.    // the maximum length of the message that we want to print to the screen  
    44.    private static final int MAX_OUTPUT_MESSAGE_SIZE = 256;  
    45.   
    46.   
    47.    private static int OK_RC = 200;  
    48.   
    49.      
    50.    /** 
    51.     * 构建订阅主题队列路径 
    52.     *  
    53.     * @param host 
    54.     * @param port 
    55.     * @param context 
    56.     * @param queueName 
    57.     */  
    58.     private static String getPublishQueueURL(String host, String port,  
    59.             String context, String queueName) {  
    60.         StringBuffer urlString =new StringBuffer("http://");  
    61.            if(StringUtils.isEmtry(host)){  
    62.                host=DEFAULT_HOST;  
    63.            }  
    64.              
    65.            if(StringUtils.isEmtry(port)){  
    66.                port=DEFAULT_PORT;  
    67.            }  
    68.            urlString.append(host).append(":").append(port);  
    69.            if(StringUtils.isEmtry(context)){  
    70.                context=DEFAULT_CONTEXT_ROOT;  
    71.            }  
    72.            urlString.append("/");  
    73.            urlString.append(context);  
    74.            urlString.append("/msg/queue/");  
    75.            if(StringUtils.isEmtry(queueName)){  
    76.                queueName=DEFAULT_QUEUE;  
    77.            }  
    78.            urlString.append(queueName);  
    79.            System.out.println("urlString="+urlString);  
    80.            return urlString.toString();  
    81.     }  
    82.   
    83.       
    84.     /** 
    85.      *  通过HTTP POST 订阅主题的具体实现 
    86.      * @param host 
    87.      * @param port 
    88.      * @param context 
    89.      * @param queueName 
    90.      * @return 
    91.      * @throws MalformedURLException 
    92.      */  
    93.        public static boolean subTopic(String host,String port,String context,String queueName ){  
    94.               String publishURL=getPublishQueueURL(host, port, context, queueName);  
    95.               URL url=null;  
    96.               HttpURLConnection connection=null;  
    97.                 try {  
    98.                       url = new URL(publishURL);  
    99.                       connection= (HttpURLConnection) url.openConnection();  
    100.                       /* Build the headers */  
    101.                       // the verb first.  
    102.                       connection.setRequestMethod("DELETE");  
    103.           
    104.                       // write out what headers we want back  
    105.                       // the header names are case-sensitive  
    106.                       connection.setRequestProperty("x-msg-require-headers",  
    107.                             "timestamp, expiry, persistence");  
    108.           
    109.                       // Now actually send the request message. There is no content as this is a  
    110.                       // DELETE  
    111.                       connection.connect();  
    112.                       String formattedMessage = null;  
    113.                       // check the response for errors  
    114.                       int responseCode = connection.getResponseCode();  
    115.                     if (responseCode == OK_RC)  
    116.                       {  
    117.                          // Get the headers first  
    118.                          String timestamp = connection.getHeaderField("x-msg-timestamp");  
    119.                          String expiry = connection.getHeaderField("x-msg-expiry");  
    120.                          String persistence = connection.getHeaderField("x-msg-persistence");  
    121.                          // now get the message data  
    122.                          BufferedReader reader = new BufferedReader(new InputStreamReader(  
    123.                                connection.getInputStream()));  
    124.                          String line = null;  
    125.                          StringBuffer messageBuffer = new StringBuffer();  
    126.                          while ((line = reader.readLine()) != null)  
    127.                          {  
    128.                             messageBuffer.append(line);  
    129.                          }  
    130.                          String messageBody = messageBuffer.toString();  
    131.                           
    132.                            
    133.                          formattedMessage = MESSAGE_BOUNDARY + newline;  
    134.                          // Which is greater the max output message size or the message length?  
    135.                          int messageSizeToPrint = messageBody.length() > MAX_OUTPUT_MESSAGE_SIZE ? MAX_OUTPUT_MESSAGE_SIZE  
    136.                                : messageBody.length();  
    137.                          formattedMessage += messageBody.substring(0, messageSizeToPrint)  
    138.                                + newline;  
    139.                          formattedMessage += "timestamp   = " + timestamp + newline;  
    140.                          formattedMessage += "expiry      = " + expiry + newline;  
    141.                          formattedMessage += "persistence = " + persistence + newline;  
    142.                            
    143.                          System.out.println("formattedMessage "+formattedMessage);  
    144.                       }else{  
    145.                           String responseMessage =connection.getResponseMessage();  
    146.                           System.out.println("responsere sponseCode "+responseCode+" response request ="+responseMessage);  
    147.                       }  
    148.                 } catch (MalformedURLException e) {  
    149.                     // TODO Auto-generated catch block  
    150.                     e.printStackTrace();  
    151.                 } catch (IOException e) {  
    152.                     // TODO Auto-generated catch block  
    153.                     e.printStackTrace();  
    154.                 }finally{  
    155.                     connection.disconnect();  
    156.                 }  
    157.            return false;  
    158.        }  
    159.   
    160.         public static void main(String[] args) {  
    161.            HTTPDELETE.subTopic("192.168.208.46", "8080", "mq", "java_lover");  
    162.         }  
    163.   
    164. }  
  • 相关阅读:
    重启Linux机器异常的解决方法
    SSH连接Linux服务器异常
    H5本地存储
    Spring MVC概述
    Linux下oracle开机自启动
    [ASP.NET MVC]@Partial 和@RenderPartial的区别
    [ASP.NET MVC]EntityFramework离线部署
    [ASP.NET MVC]@RenderSection,@RenderBody(),@RenderPage
    [ASP.NET MVC]@Html.AntiForgeryToken() 防止CSRF攻击
    [ASP.NET MVC]@Scripts.Render、@Styles.Render的使用
  • 原文地址:https://www.cnblogs.com/yudar/p/4613748.html
Copyright © 2020-2023  润新知