1.其中用到的是Https協議,已經封裝好了,能夠直接調用。 java
package com.common.sms.http; import java.io.IOException; import net.sf.json.JSONException; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.common.sms.Message; import com.common.weibo.weibo4j.model.MySSLSocketFactory; /** HttpMessage用於封裝請求併發送消息 * * @author * @version 2011-11-30 * @see [相關類/方法] */ public class HttpMessage { Log log = LogFactory.getLog(HttpMessage.class); /** 設置消息頭、參數 * * @param message * 短息信息 * @param URL * 請求的URL * @return 是否成功 * @exception Exception */ public Integer httpPostRequest(Message message, String URL, String appKey, String appSecret) { SmsAuth smsAuth = new SmsAuth(); String token = smsAuth.getToken(appKey, appSecret); String authorization = "appKey=" + '"' + appKey + '"' + ",token=" + '"' + token + '"'; log.info("authorization----------->" + authorization); Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); // 定義http客戶端對象--httpClient HttpClient httpClient = new HttpClient(); // 定義並實例化客戶端連接對象-GetMethod PostMethod postMethod = new PostMethod(URL); // 定義返回結果碼 Integer resultCode = -1; // 設置http的頭 postMethod.setRequestHeader("Authorization", authorization); postMethod.setRequestHeader("Content-Type", "application/json;charset=utf-8"); postMethod.setRequestHeader("Accept", "application/json"); // 設置請求參數 JSONObject jsonMessage = new JSONObject(); JSONObject json = new JSONObject(); jsonMessage.put("to", message.getToPhone()); jsonMessage.put("from", message.getFromPhone()); jsonMessage.put("content", message.getMsc()); json.put("message", jsonMessage); json.put("notifyURL", "http://10.138.38.51:8080/notifications/DeliveryInfoNotification"); log.info("json----------->" + json); resultCode = httpRequest(httpClient, postMethod, json); return resultCode; } /** 請求發送 * * @param HttpClient * @param PostMethod * @param JSONObject * @return 是否成功 * @exception Exception */ @SuppressWarnings("deprecation") public Integer httpRequest(HttpClient httpClient, PostMethod postMethod, JSONObject json) { // 響應內容 String result = ""; try { postMethod.setRequestBody(json.toString()); log.info("httpClient編碼格式:----------->" + postMethod.getRequestCharSet()); // 定義訪問地址的連接狀態 int statusCode = 0; try { // 客戶端請求url數據 statusCode = httpClient.executeMethod(postMethod); } catch (Exception e) { log.error("請求URL失敗!", e); return -1; } // 請求成功狀態-200 if (statusCode == HttpStatus.SC_OK) { try { // 獲取請求響應結果 result = postMethod.getResponseBodyAsString(); log.info("result----------->" + result); } catch (IOException e) { log.error("獲取請求響應結果失敗!", e); return -1; } } else { log.error("訪問地址請求失敗!:" + statusCode); return -1; } } catch (Exception e) { log.error(e.getMessage(), e); return -1; } finally { // 釋放連接 postMethod.releaseConnection(); httpClient.getHttpConnectionManager().closeIdleConnections(0); } // 解析響應結果 JSONObject jsonResult = null; try { jsonResult = JSONObject.fromObject(result); } catch (JSONException e) { log.error("獲取的Http響應結果格式錯誤!", e); return -1; } Integer resultCode = jsonResult.getInt("resultCode"); log.info(result); log.info("resultCode:----------->" + result); return resultCode; } }
2. apache
package com.conmon.weibo.weibo4j.model; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; /** * Provide a custom socket factory that implements org.apache.commons.httpclient.protocol.ProtocolSocketFactory * interface. The socket factory is responsible for opening a socket to the target server using either the standard or a * third party SSL library and performing any required initialization such as performing the connection handshake. * Generally the initialization is performed automatically when the socket is created. * * @author sinaWeibo */ public class MySSLSocketFactory implements ProtocolSocketFactory { private SSLContext sslcontext = null; private SSLContext createSSLContext() { SSLContext sslcontext = null; try { sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return sslcontext; } private SSLContext getSSLContext() { if (this.sslcontext == null) { this.sslcontext = createSSLContext(); } return this.sslcontext; } public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); } public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(host, port); } public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort); } public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); SocketFactory socketfactory = getSSLContext().getSocketFactory(); if (timeout == 0) { return socketfactory.createSocket(host, port, localAddress, localPort); } else { Socket socket = socketfactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.bind(localaddr); socket.connect(remoteaddr, timeout); return socket; } } private static class TrustAnyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } } }