HTTP和MQTT

任务要求

一. 安装Java开发环境和Java IDE编程工具 Eclipse 或 IDEA,基于HTTP协议(严格地说是 “REST接口规范”)读取互联网上web服务网站实现:
1)读取指定城市的天气预报信息;2)给指定手机号码发送验证码;
提示:参考课堂上给的培训视频和课件资料。 二. 学习和熟悉MQTT 协议
1)在本机上安装MQTT服务器和客户端软件,练习消息发布与订阅,比如自定义一个天气预报的消息主题。 提示:可以利用课堂教学资料或网上资源。
2)利用网上提供的MQTT服务,编写MQTT客户端程序(python、java或c#、c/c++,任意一种编程语言),自定义一个天气预报主题,完成订阅与发布。思考MQTT与前面REST协议的区别。

HTTP协议

获得各地天气预报的信息

环境:eclipse

package abaaba;

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

public class aba {

	public static void main(String[] args) throws IOException {
				//1. 	先准备一个URL类的对象 u
				URL url = new URL("http://api.map.baidu.com/weather/v1/?district_id=500108&data_type=all&ak=pKGfwLXpAaWo7U72R7MgpYpFrhibOoFR\r\n"
						+ "\r\n"
						+ "");
				//2. 	打开服务器连接,得到连接对象 conn
				URLConnection conn = url.openConnection();
				//3. 	获取加载数据的字节输入流 is
				InputStream is = conn.getInputStream();
				//4.	将is装饰为能一次读取一行的字符输入流 br
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				//5.	加载一行数据
				String text = br.readLine();
				//6.	显示
				System.out.println(text);
				//5.	加载一行数据
				//7.	释放资源
				br.close();
	}

}

结果显示
在这里插入图片描述

给指定手机发送验证码

HttpClientUtil.java

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
  
  
public class HttpClientUtil {  
    private RequestConfig requestConfig = RequestConfig.custom()  
            .setSocketTimeout(15000)  
            .setConnectTimeout(15000)  
            .setConnectionRequestTimeout(15000)  
            .build();  
      
    private static HttpClientUtil instance = null;  
    private HttpClientUtil(){}  
    public static HttpClientUtil getInstance(){  
        if (instance == null) {  
            instance = new HttpClientUtil();  
        }  
        return instance;  
    }  
      
    /** 
     * 发送 post请求 
     * @param httpUrl 地址 
     */  
    public String sendHttpPost(String httpUrl) {  
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost    
        return sendHttpPost(httpPost,"utf-8");  
    }  
      
      
    /** 
     * 发送 post请求 
     * @param httpUrl 地址 
     * @param maps 参数 
     *  @param type 字符编码格式 
     */  
    public String sendHttpPost(String httpUrl, Map<String, String> maps,String type) {  
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost    
        // 创建参数队列    
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
        for (String key : maps.keySet()) {  
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));  
        }  
        try {  
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, type));  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return sendHttpPost(httpPost,type);  
    }  
      
    /** 
     * 发送Post请求 
     * @param httpPost 
     * @return 
     */  
    private String sendHttpPost(HttpPost httpPost,String reponseType) {  
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;  
        String responseContent = null;  
        try {  
            // 创建默认的httpClient实例.  
            httpClient = HttpClients.createDefault();  
            httpPost.setConfig(requestConfig);  
            // 执行请求  
            response = httpClient.execute(httpPost);  
            entity = response.getEntity();  
            responseContent = EntityUtils.toString(entity, reponseType);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                // 关闭连接,释放资源  
                if (response != null) {  
                    response.close();  
                }  
                if (httpClient != null) {  
                    httpClient.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return responseContent;  
    }  
  
    /** 
     * 发送 get请求 
     * @param httpUrl 
     */  
    public String sendHttpGet(String httpUrl) {  
        HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求  
        return sendHttpGet(httpGet);  
    }  
      
    /** 
     * 发送 get请求Https 
     * @param httpUrl 
     */  
    public String sendHttpsGet(String httpUrl) {  
        HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求  
        return sendHttpsGet(httpGet);  
    }  
    
    /**
     * @Title: sendMsgUtf8
     * @Description: TODO(发送utf8)
     * @param: @param Uid
     * @param: @param Key
     * @param: @param content
     * @param: @param mobiles
     * @param: @return      
     * @date: 2017-3-22 下午5:58:07
     * @throws
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public int sendMsgUtf8(String Uid,String Key,String content,String mobiles){
    	Map maps = new HashMap();
		maps.put("Uid", Uid);
		maps.put("Key", Key);
		maps.put("smsMob", mobiles);
		maps.put("smsText", content);
		String result = sendHttpPost("http://utf8.sms.webchinese.cn", maps, "utf-8");
		return Integer.parseInt(result);
    }
    
    /**
     * @Title: sendMsgUtf8
     * @Description: TODO(发送utf8)
     * @param: @param Uid
     * @param: @param Key
     * @param: @param content
     * @param: @param mobiles
     * @param: @return     
     * @return: int     
     * @author:  ly
     * @date: 2017-3-22 下午5:58:07
     * @throws
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public int sendMsgGbk(String Uid,String Key,String content,String mobiles){
    	Map maps = new HashMap();
		maps.put("Uid", Uid);
		maps.put("Key", Key);
		maps.put("smsMob", mobiles);
		maps.put("smsText", content);
		String result = sendHttpPost("http://gbk.sms.webchinese.cn", maps, "gbk");
		return Integer.parseInt(result);
    }
      
    /** 
     * 发送Get请求 
     * @param httpPost 
     * @return 
     */  
    private String sendHttpGet(HttpGet httpGet) {  
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;  
        String responseContent = null;  
        try {  
            // 创建默认的httpClient实例.  
            httpClient = HttpClients.createDefault();  
            httpGet.setConfig(requestConfig);  
            // 执行请求  
            response = httpClient.execute(httpGet);  
            entity = response.getEntity();  
            responseContent = EntityUtils.toString(entity, "UTF-8");  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                // 关闭连接,释放资源  
                if (response != null) {  
                    response.close();  
                }  
                if (httpClient != null) {  
                    httpClient.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return responseContent;  
    }  
      
    /** 
     * 发送Get请求Https 
     * @param httpPost 
     * @return 
     */  
    private String sendHttpsGet(HttpGet httpGet) {  
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;  
        String responseContent = null;  
        try {  
            // 创建默认的httpClient实例.  
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));  
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);  
            httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();  
            httpGet.setConfig(requestConfig);  
            // 执行请求  
            response = httpClient.execute(httpGet);  
            entity = response.getEntity();  
            responseContent = EntityUtils.toString(entity, "UTF-8");  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                // 关闭连接,释放资源  
                if (response != null) {  
                    response.close();  
                }  
                if (httpClient != null) {  
                    httpClient.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return responseContent;  
    }  
    
    /**
	 * @Title: getErrorMsg
	 * @Description: TODO(返回异常原因)
	 * @param: @param errorCode
	 */
	public String getErrorMsg(int errorCode){
		if(errorCode==-1){
			return "没有该用户账户";
		}else if(errorCode==-2){
			return "接口密钥不正确";
		}else if(errorCode==-3){
			return "短信数量不足";
		}else if(errorCode==-4){
			return "手机号格式不正确";
		}else if(errorCode==-21){
			return "MD5接口密钥加密不正确";
		}else if(errorCode==-11){
			return "该用户被禁用";
		}else if(errorCode==-14){
			return "短信内容出现非法字符";
		}else if(errorCode==-41){
			return "手机号码为空";
		}else if(errorCode==-42){
			return "短信内容为空";
		}else if(errorCode==-51){
			return "短信签名格式不正确";
		}else if(errorCode==-6){
			return "IP限制";
		}else{
			return "未知错误码:"+errorCode;
		}
	}
}  

test.java

import java.util.HashMap;
import java.util.Map;

/**  
 * @Title: http://www.smschinese.cn/api.shtml
 * @date 2011-3-22
 * @version V1.2  
 */
public class test {
	
	//用户名
	private static String Uid = "wdw123";
	
	//接口安全秘钥
	private static String Key = "接口秘钥";
	
	//手机号码,多个号码如13800000000,13800000001,13800000002
	private static String smsMob = "接收短信号码";
	
	//短信内容格式如下
	private static String smsText = "【XXX(中文)】验证码:XXX";
	
	
	public static void main(String[] args) {
		
		HttpClientUtil client = HttpClientUtil.getInstance();
		
		//UTF发送
		int result = client.sendMsgUtf8(Uid, Key, smsText, smsMob);
		if(result>0){
			System.out.println("UTF8成功发送条数=="+result);
		}else{
			System.out.println(client.getErrorMsg(result));
		}
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值