1. 程式人生 > >使用httpClient傳送簡訊大體格式

使用httpClient傳送簡訊大體格式

package com.hjsj.service.dt.sendSms;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import com.hjsj.hrms.interfaces.sys.SmsProxy;
import com.hrms.struts.constant.SystemConfig;
import com.hrms.struts.exception.GeneralException;

public class SmsWG implements SmsProxy {

	
	public boolean sendMessage(String phone, String msg) {
		//大唐簡訊閘道器IP
		String ip = "";
		//大唐簡訊閘道器埠
		String port = "";
		//大唐簡訊閘道器使用者名稱
		String user = "";
		//大唐簡訊閘道器密碼
		String pwd = "";
		//大唐簡訊閘道器標識
		String flag = "";
		try {
			ip = SystemConfig.getProperty("dt_message_ip");
			port = SystemConfig.getProperty("dt_message_port");
			user = SystemConfig.getProperty("dt_message_user");
			pwd = SystemConfig.getProperty("dt_message_pwd");
			flag = SystemConfig.getProperty("dt_message_flag");
		} catch (GeneralException e1) {
			e1.printStackTrace();
		}
		
		// 構造HttpClient的例項
		HttpClient httpClient = new HttpClient();

		// 建立GET方法的例項
		
		GetMethod getMethod = null;
		try {
			getMethod = new GetMethod("http://" + ip + ":" + port
					+ "//sendsmd.asmx/send?User=" + user + "&Pwd=" + pwd
					+ "&Falgid=" + flag + "&Phone=" + phone + "&Content=" +  URLEncoder.encode(msg, "utf-8")
					+ "");;
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
				
		// 使用系統提供的預設的恢復策略
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler());
		try {
			// 執行getMethod
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: "
						+ getMethod.getStatusLine());
			}
			// 讀取內容
			byte[] responseBody = getMethod.getResponseBody();
			// 處理內容
			//System.out.println(new String(responseBody));
			
			return true;
			
		} catch (HttpException e) {
			// 發生致命的異常,可能是協議不對或者返回的內容有問題
			System.out.println("Please check your provided http address!");
			e.printStackTrace();
		} catch (IOException e) {
			// 發生網路異常
			e.printStackTrace();
		} finally {
			// 釋放連線
			getMethod.releaseConnection();
		}
		return false;
	}


}