`
longgangbai
  • 浏览: 7342974 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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 diagramSkip 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 diagramSkip 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

Path
See URI Format.
HTTP version
HTTP version; for example, HTTP/1.1
general-header
See HTTP/1.1 - 4.5 General Header Fields.
request-header
See 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

Path
See URI Format.
HTTP version
HTTP version; for example, HTTP/1.1
general-header
See HTTP/1.1 - 4.5 General Header Fields.
response-header
See 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.
Message
Message 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, or 0-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-headers request 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订阅主题信息

package com.etrip.mqttv3.http;
/**
 * This sample shows how to delete a message. It has slightly enhanced function
 * of the amqsget command in that it will print out the timestamp, expiry and
 * persistence of the messages. The program continues until the queue is empty
 * or a request fails. This program can potentially take in three parameters:
 * <queueName>
 * <host:port> <context-root (the MQ Bridge for HTTP's context-root)>
 * defaults are: SYSTEM.DEFAULT.LOCAL.QUEUE localhost:8080 mq 
 * 
 * If there are any exceptions thrown from this program or errors returned from the server then they are 
 * printed to standard output as-is.
 *   
 * No more messages
 * HTTP DELETE Sample end
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
 * 
 * 采用HTTP DELETE方式的订阅相关的MQTT的主题的信息
 * 
 * @author longgangbai
 * 
 * 
 */
public class HTTPDELETE
{
   private static final String DEFAULT_HOST = "localhost";
   private static final String DEFAULT_PORT = "8080";
   private static final String DEFAULT_QUEUE = "SYSTEM.DEFAULT.LOCAL.QUEUE";

   private static final String DEFAULT_CONTEXT_ROOT = "mq";

   public static String newline = System.getProperty("line.separator");

   private static final String MESSAGE_BOUNDARY = "_________________________________________________________________________________________";

   // the maximum length of the message that we want to print to the screen
   private static final int MAX_OUTPUT_MESSAGE_SIZE = 256;


   private static int OK_RC = 200;

   
   /**
    * 构建订阅主题队列路径
    * 
    * @param host
    * @param port
    * @param context
    * @param queueName
    */
	private static String getPublishQueueURL(String host, String port,
			String context, String queueName) {
		StringBuffer urlString =new StringBuffer("http://");
		   if(StringUtils.isEmtry(host)){
			   host=DEFAULT_HOST;
		   }
		   
		   if(StringUtils.isEmtry(port)){
			   port=DEFAULT_PORT;
		   }
		   urlString.append(host).append(":").append(port);
		   if(StringUtils.isEmtry(context)){
			   context=DEFAULT_CONTEXT_ROOT;
		   }
		   urlString.append("/");
		   urlString.append(context);
		   urlString.append("/msg/queue/");
		   if(StringUtils.isEmtry(queueName)){
			   queueName=DEFAULT_QUEUE;
		   }
		   urlString.append(queueName);
		   System.out.println("urlString="+urlString);
		   return urlString.toString();
	}

	
	/**
	 *  通过HTTP POST 订阅主题的具体实现
	 * @param host
	 * @param port
	 * @param context
	 * @param queueName
	 * @return
	 * @throws MalformedURLException
	 */
	   public static boolean subTopic(String host,String port,String context,String queueName ){
		      String publishURL=getPublishQueueURL(host, port, context, queueName);
		      URL url=null;
		      HttpURLConnection connection=null;
				try {
					  url = new URL(publishURL);
					  connection= (HttpURLConnection) url.openConnection();
				      /* Build the headers */
				      // the verb first.
				      connection.setRequestMethod("DELETE");
		
				      // write out what headers we want back
				      // the header names are case-sensitive
				      connection.setRequestProperty("x-msg-require-headers",
				            "timestamp, expiry, persistence");
		
				      // Now actually send the request message. There is no content as this is a
				      // DELETE
				      connection.connect();
				      String formattedMessage = null;
				      // check the response for errors
				      int responseCode = connection.getResponseCode();
					if (responseCode == OK_RC)
				      {
				         // Get the headers first
				         String timestamp = connection.getHeaderField("x-msg-timestamp");
				         String expiry = connection.getHeaderField("x-msg-expiry");
				         String persistence = connection.getHeaderField("x-msg-persistence");
				         // now get the message data
				         BufferedReader reader = new BufferedReader(new InputStreamReader(
				               connection.getInputStream()));
				         String line = null;
				         StringBuffer messageBuffer = new StringBuffer();
				         while ((line = reader.readLine()) != null)
				         {
				            messageBuffer.append(line);
				         }
				         String messageBody = messageBuffer.toString();
						
				         
				         formattedMessage = MESSAGE_BOUNDARY + newline;
				         // Which is greater the max output message size or the message length?
				         int messageSizeToPrint = messageBody.length() > MAX_OUTPUT_MESSAGE_SIZE ? MAX_OUTPUT_MESSAGE_SIZE
				               : messageBody.length();
				         formattedMessage += messageBody.substring(0, messageSizeToPrint)
				               + newline;
				         formattedMessage += "timestamp   = " + timestamp + newline;
				         formattedMessage += "expiry      = " + expiry + newline;
				         formattedMessage += "persistence = " + persistence + newline;
				         
				         System.out.println("formattedMessage "+formattedMessage);
				      }else{
				    	  String responseMessage =connection.getResponseMessage();
				    	  System.out.println("responsere sponseCode "+responseCode+" response request ="+responseMessage);
				      }
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					connection.disconnect();
				}
		   return false;
	   }

        public static void main(String[] args) {
     	   HTTPDELETE.subTopic("192.168.208.46", "8080", "mq", "java_lover");
		}

}

 

 

分享到:
评论

相关推荐

    基于Java的netty-mqtt MQTT 3.1.1协议服务端与客户端设计源码

    netty-mqtt是一个基于Java开发的MQTT 3.1.1协议服务端与客户端,包含113个文件,其中包括87个Java源文件、8个XML文件、7个Iml文件、3个YAML文件、3个JKS文件、2个Factories文件、1个LICENSE文件和1个Markdown文件。...

    基于MQTT推送服务端java实现

    MQTT(Message Queuing Telemetry Transport)是一种...通过学习和理解以上知识点,并结合提供的代码进行研究,你应该能够搭建和运行一个基本的MQTT服务端。不断迭代和优化,你的服务器将能适应各种复杂的需求和场景。

    C# 基于MQTTNet的服务端与客户端通信案例

    MQTT(Message Queuing Telemetry Transport)是一种轻量级的发布/订阅消息协议,常用于物联网(IoT)应用,因为它对网络带宽的要求低,且能够可靠地处理不稳定网络环境。 首先,我们从服务端开始。MQTT服务端,...

    MQTT C# demo测试案例 包含服务端客户端

    MQTT基于发布/订阅模式,其中消息发布者将数据发送到特定主题,而消息订阅者则通过订阅这些主题来接收数据。这种模式非常适合资源有限的设备,如嵌入式系统和移动设备,因为它具有低带宽、低功耗和高可靠性。 在C#...

    Winform中使用MQTTnet实现MQTT的服务端和客户端之间的通信以及将订阅的消息保存到文件示例代码.rar

    Winform中使用MQTTnet实现MQTT的服务端和客户端之间的通信以及将订阅的消息保存到文件示例代码.rar Winform中使用MQTTnet实现MQTT的服务端和客户端之间的通信以及将订阅的消息保存到文件示例代码.rar Winform中使用...

    MQTTnet 在.net core中的应用--服务端+订阅发布客户端(支持阿里云mqtt)

    MQTT是一种基于发布/订阅模式的消息协议,广泛应用于物联网、移动应用、小型设备等场景。其特点包括低开销、小延迟、网络连接可靠性高以及发布者与订阅者解耦。 **2. MQTTnet服务端** 创建MQTTnet服务器时,首先...

    AspNetCore基于MQTTnet.AspNetCore3.0.9的服务端实例(支持Websocket)

    官方下载的MQTTNet服务端实例用的基于MQTTNet的服务端,不支持Websocket交互,通过反复查阅资料,使用基于.Net Core(3.1) 和MQTTnet.AspNetCore(3.0.9)的服务端程序可以实现同时支持cs客户端、Websocket客户端的...

    MQTT服务端

    MQTT(Message Queuing Telemetry Transport)是一种轻量级、基于发布/订阅模式的网络通信协议,常用于物联网(IoT)设备之间的数据传输。它设计的目标是减少网络带宽和设备资源,确保低功耗设备在不稳定网络环境下...

    MQTT服务端和客户端工具

    因在工作中经常有用到MQTT做消息的收发,每次调试过程中,经常需要查看接收的消息内容以及人为发送消息,为便于个人在工作中开发和调试,于是,就萌生了自己写一个简单又好用的MQTT服务端和客户端的想法。...

    mqtt+服务端+客户端

    `Mqtt-Clinet-Window-测试工具.zip`可能包含了一个适用于Windows平台的MQTT客户端测试工具,用于模拟真实的客户端行为,测试与服务端的连接、发布消息、订阅主题等功能。这样的工具对于开发和调试MQTT应用非常有用,...

    mqtt服务端搭建到android使用教程

    MQTT(Message Queuing Telemetry Transport)是一种轻量级的发布/订阅消息协议,常用于物联网(IoT)设备之间的通信。本教程将指导你如何搭建MQTT服务端,并将其集成到Android应用中。 **一、MQTT服务端搭建** 1. *...

    MQTT服务端客户端测试工具

    MQTT(Message Queuing Telemetry Transport)是一种轻量级的发布/订阅消息协议,常用于物联网(IoT)设备之间的通信。这种协议设计的目标是高效、可靠且低开销,尤其适合于资源有限的设备和网络条件不稳定的环境。在...

    Mqtt发布与订阅功能示例代码

    MQTT(Message Queuing Telemetry Transport)是一种轻量级的发布/订阅消息协议,常用于物联网(IoT)设备之间的通信。这个压缩包包含了两个Visual Studio 2010工程,`MqttPubTest`和`MqttSubTest`,分别用于实现MQTT...

    C#使用 MQTTnet 快速实现 MQTT 通信 Demo

    MQTT(Message Queuing Telemetry Transport)是一种轻量级的发布/订阅式消息协议,广泛应用于物联网(IoT)场景,因为它具有低开销、高可靠性以及适用于受限网络的特点。在Windows 7环境下,使用Visual Studio 2017...

    基于netty实现mqtt协议 服务器端开发,可解码http、mqtt协议请求

    1.基于netty绑定端口监听,对于mqtt消息和http请求消息分别绑定不同的监听端口; 2.在MQTTServerInitializer中,分别添加mqtt编码解码器和http编码解码器,并分别将自定义的mqtt消息处理handle类和http消息handle类...

    java实现mqtt的发送和订阅

    在本文中,我们将深入探讨如何使用Java来实现MQTT(Message Queuing Telemetry Transport)协议的发送和订阅功能。MQTT是一种轻量级的发布/订阅消息传输协议,广泛应用于物联网(IoT)设备间的数据通信。我们将使用...

    C#实现消息发布订阅即时通信Mqtt

    本文将详细讲解如何使用C#语言实现基于Mqtt协议的消息发布订阅功能,帮助开发者快速理解和应用这一技术。 Mqtt(Message Queuing Telemetry Transport),即消息队列遥测传输协议,是一种轻量级的发布/订阅消息协议...

    delphi Mqtt服务端和客户端源码

    Delphi MQTT服务端和客户端源码是一套基于Delphi编程语言实现的...通过深入研究源码,开发者可以了解到如何使用Indy组件进行网络编程,以及如何实现MQTT的发布/订阅模型,这对于扩展或定制自己的物联网应用非常有帮助。

    C#使用MQTT测试,客户端和服务端

    C#使用MQTT测试

    Mqtt通讯客户端和服务端代码

    MQTT(Message Queuing Telemetry Transport)是一种轻量级的发布/订阅消息协议,常用于物联网、移动应用和低带宽、高延迟或不可靠的网络环境。本项目提供了MQTT服务器和客户端的C#实现,旨在帮助开发者更好地理解和...

Global site tag (gtag.js) - Google Analytics