HttpMessage用于封装请求并发送消息

1.其中用到的是Https协议,已经封装好了,可以直接调用。


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.

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[] {};
        }
    }
}


你可能感兴趣的:(HttpMessage)