1. 程式人生 > >java實現emqtt的訊息釋出

java實現emqtt的訊息釋出

package com.hthl.xxtd.sdk.push.emqtt;

import javax.resource.spi.CommException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

import com.hthl.xxtd.util.DateUtil;

/**
 * EMQ客戶端工具
 * */
public class EmqHttpUtil {
	private static final Logger logger = Logger.getLogger(EmqHttpUtil.class);
	
	public static void main(String[] args) throws Exception {
		NameValuePair[] data={
				new NameValuePair("qos", "1"),
				new NameValuePair("retain", "0"),
				new NameValuePair("topic", "hthl/hyt"),
				new NameValuePair("message", "大吉大利,今晚吃雞:"+DateUtil.getTimes())
				};
		System.out.println(httpPost("http://192.168.20.38:6060/mqtt/publish", data, "UTF-8",getHeader()));
	}
	
	/** * 構造Basic Auth認證頭資訊
	 * @throws Exception */
	private static String getHeader() throws Exception { 
		String auth = "hthl_sub" + ":" + "123456";
		byte[] encodedAuth=Base64.encodeBase64(auth.getBytes("UTF-8"));
		String authHeader = "Basic " +new String(encodedAuth);
		return authHeader;
	}
	
	/**
	 * HTTP/HTTPS POST
	 * @param url 介面地址
	 * @param data 請求資料
	 * @param encoding 編碼方式
	 * @return String
	 * @throws CommException
	 */
	public static String httpPost(String url, NameValuePair[] data,String encoding,String authHeader)throws Exception {
		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(url);
		// 設定編碼,http post同時會用編碼進行url.encode
		httpClient.getParams().setContentCharset(encoding);
        postMethod.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset="+encoding);
        postMethod.addRequestHeader("Authorization", authHeader);
		// 將表單的值放入postMethod中
		postMethod.setRequestBody(data);
		// 執行postMethod
		int statusCode =httpClient.executeMethod(postMethod);
		 logger.info("Response status code: " + statusCode);//返回200為成功
		// HttpClient對於要求接受後繼服務的請求,POST和PUT等不能自動處理轉發
		// 301或者302
		if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
			// 從頭中取出轉向的地址
			Header locationHeader = postMethod.getResponseHeader("location");
			String location = null;
			if (locationHeader != null) {
				location = locationHeader.getValue();
				logger.error("The page was redirected to:" + location);
			} else {
				logger.error("Location field value is null.");
			}
			return null;
		} else {
			return postMethod.getResponseBodyAsString();
		}
	}
}