HTTP和MQTT协议实践

一、REST协议实现

任务要求一
安装Java开发环境和Java IDE编程工具 Eclipse 或 IDEA,基于HTTP协议(严格地说是 “REST接口规范”)读取互联网上web服务网站实现:
1)读取指定城市的天气预报信息;
2)给指定手机号码发送验证码;

1. 读取指定城市的天气预报信息

代码如下

package tianqi;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class WeatherDemo {
    
    

 private static String makeSoapRequest(String method,String paramName,String paramValue) {
    
    
  StringBuffer sb = new StringBuffer();
  sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
  sb.append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
  sb.append("xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
  sb.append("<soap:Body><"+method+" xmlns=\"http://WebXml.com.cn/\"><"+paramName+">" + paramValue + "</"+paramName+"></"+method+"></soap:Body>");
  sb.append("</soap:Envelope>");
  return sb.toString();
 }

 private static InputStream getSoapInputStream(String method,String paramName,String paramValue) throws Exception {
    
    
  try {
    
    
   String soap = makeSoapRequest(method,paramName,paramValue);
   if (soap == null) {
    
    
    return null;
   }

   URL url = new URL("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx");   
   URLConnection conn = url.openConnection();
   conn.setUseCaches(false);
   conn.setDoInput(true);
   conn.setDoOutput(true);
   conn.setRequestProperty("Content-Length", Integer.toString(soap.length()));
   conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
   OutputStream os = conn.getOutputStream();
   OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
   osw.write(soap);
   osw.flush();
   osw.close();
   InputStream is = conn.getInputStream();
   return is;
  } catch (Exception e) {
    
    
   e.printStackTrace();
   return null;
  }
 }
 
 public static String getWeather(String city) {
    
       
        try {
    
       
            Document doc;   
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
            dbf.setNamespaceAware(true);   
            DocumentBuilder db = dbf.newDocumentBuilder();   
            InputStream is = getSoapInputStream("getWeatherbyCityName","theCityName",city);   
            doc = db.parse(is);   
            NodeList nl = doc.getElementsByTagName("string");   
            StringBuffer sb = new StringBuffer();   
            for (int count = 0; count < nl.getLength(); count++) {
    
       
                Node n = nl.item(count);   
                if(n.getFirstChild().getNodeValue().equals("查询结果为空!")) {
    
       
                    sb = new StringBuffer("#") ;   
                    break ;  
                }   
                sb.append(n.getFirstChild().getNodeValue() + "#\n");   
            }   
            is.close();   
            return sb.toString();   
        } catch (Exception e) {
    
       
            e.printStackTrace();   
            return null;   
        }   
    } 

 public static void main(String[] args) throws ParseException {
    
    
  System.out.println(getWeather("重庆"));   
 }

}

实现效果如下

在这里插入图片描述

2. 给指定手机号码发送验证码

主要代码

package com.kkb.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class Demo5 {
    
    

	public static void main(String[] args) throws IOException {
    
    
		
		URL url = new URL("https://itdage.com/kkb/kkbsms?key=xzk&number=18983921532&code=herui");
	
		URLConnection conn = url.openConnection();

		InputStream is = conn.getInputStream();
			
		BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));

		String text = br.readLine();
		
		System.out.println(text);
		
		br.close();

	}

}

二、MQTT协议实现

任务要求二
学习和熟悉MQTT 协议
1)在本机上安装MQTT服务器和客户端软件,练习消息发布与订阅,比如自定义一个天气预报的消息主题。
2)利用网上提供的MQTT服务,编写MQTT客户端程序(python、java或c#、c/c++,任意一种编程语言),自定义一个天气预报主题,完成订阅与发布。思考MQTT与前面REST协议的区别。

1. MQTT协议处于哪一层

众所周知,TCP/IP参考模型可以分为四层:应用层、传输层、网络层、链路层。TCP和UDP位于传输层,应用层常见的协议有HTTP、FTP、SSH等。MQTT协议运行于TCP之上,属于应用层协议,因此只要是支持TCP/IP协议栈的地方,都可以使用MQTT。

2. 自定义天气预报消息主题

MQTT服务器搭建
MQTT服务器非常多,如apache的ActiveMQ,emtqqd,HiveMQ,Emitter,Mosquitto,Moquette等等。
这里介绍的是用轻量级的mosquitto开源项目来搭建一个属于自己的MQTT服务器。
下载地址:http://mosquitto.org/files/binary/
根据平台选择相应的代码下载。

三、总结与参考资料

添加链接描述

扫描二维码关注公众号,回复: 12684399 查看本文章

猜你喜欢

转载自blog.csdn.net/lyjccchong/article/details/112197909