码迷,mamicode.com
首页 > Web开发 > 详细

http

时间:2016-12-01 17:09:51      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:this   3.2   doget   https   post请求   管理   nts   port   imp   

package com.founder.ec.common.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class HttpClientUtil {

    private static final Log logger = LogFactory.getLog(HttpClientUtil.class);
    
    public static byte[] doHttpClient(String url) {
        HttpClient c = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        try {
            getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,
                    5000);
            getMethod.getParams().setParameter(
                    HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler());
            int statusCode = c.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("doHttpClient Method failed: "
                        + getMethod.getStatusLine());
            }else{
                return getMethod.getResponseBody();
            }
        } catch (Exception e) {
            logger.error("doHttpClient errot : "+e.getMessage());
        } finally {
            getMethod.releaseConnection();
        }
        return null;
    }
    
    //财付通
    public static final String SunX509 = "SunX509";
    public static final String JKS = "JKS";
    public static final String PKCS12 = "PKCS12";
    public static final String TLS = "TLS";
    
    /**
     * get HttpURLConnection
     * @param strUrl url地址
     * @return HttpURLConnection
     * @throws IOException
     */
    public static HttpURLConnection getHttpURLConnection(String strUrl)
            throws IOException {
        URL url = new URL(strUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url
                .openConnection();
        return httpURLConnection;
    }
    
    /**
     * get HttpsURLConnection
     * @param strUrl url地址
     * @return HttpsURLConnection
     * @throws IOException
     */
    public static HttpsURLConnection getHttpsURLConnection(String strUrl)
            throws IOException {
        URL url = new URL(strUrl);
        HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url
                .openConnection();
        return httpsURLConnection;
    }
    
    /**
     * 获取不带查询串的url
     * @param strUrl
     * @return String
     */
    public static String getURL(String strUrl) {

        if(null != strUrl) {
            int indexOf = strUrl.indexOf("?");
            if(-1 != indexOf) {
                return strUrl.substring(0, indexOf);
            } 
            
            return strUrl;
        }
        
        return strUrl;
        
    }
    
    /**
     * 获取查询串
     * @param strUrl
     * @return String
     */
    public static String getQueryString(String strUrl) {
        
        if(null != strUrl) {
            int indexOf = strUrl.indexOf("?");
            if(-1 != indexOf) {
                return strUrl.substring(indexOf+1, strUrl.length());
            } 
            
            return "";
        }
        
        return strUrl;
    }
    
    /**
     * 查询字符串转换成Map<br/>
     * name1=key1&name2=key2&...
     * @param queryString
     * @return
     */
    public static Map queryString2Map(String queryString) {
        if(null == queryString || "".equals(queryString)) {
            return null;
        }
        
        Map m = new HashMap();
        String[] strArray = queryString.split("&");
        for(int index = 0; index < strArray.length; index++) {
            String pair = strArray[index];
            HttpClientUtil.putMapByPair(pair, m);
        }
        
        return m;
        
    }
    
    /**
     * 把键值添加至Map<br/>
     * pair:name=value
     * @param pair name=value
     * @param m
     */
    public static void putMapByPair(String pair, Map m) {
        
        if(null == pair || "".equals(pair)) {
            return;
        }
        
        int indexOf = pair.indexOf("=");
        if(-1 != indexOf) {
            String k = pair.substring(0, indexOf);
            String v = pair.substring(indexOf+1, pair.length());
            if(null != k && !"".equals(k)) {
                m.put(k, v);
            }
        } else {
            m.put(pair, "");
        }
    }
    
    /**
     * BufferedReader转换成String<br/>
     * 注意:流关闭需要自行处理
     * @param reader
     * @return String
     * @throws IOException
     */
    public static String bufferedReader2String(BufferedReader reader) throws IOException {
        StringBuffer buf = new StringBuffer();
        String line = null;
        while( (line = reader.readLine()) != null) {
            buf.append(line);
            buf.append("\r\n");
        }
                
        return buf.toString();
    }
    
    /**
     * 处理输出<br/>
     * 注意:流关闭需要自行处理
     * @param out
     * @param data
     * @param len
     * @throws IOException
     */
    public static void doOutput(OutputStream out, byte[] data, int len) 
            throws IOException {
        int dataLen = data.length;
        int off = 0;
        while(off < dataLen) {
            if(len >= dataLen) {
                out.write(data, off, dataLen);
            } else {
                out.write(data, off, len);
            }
            
            //刷新缓冲区
            out.flush();
            
            off += len;
            
            dataLen -= len;
        }
        
    }
    
    /**
     * 获取SSLContext
     * @param trustFile 
     * @param trustPasswd
     * @param keyFile
     * @param keyPasswd
     * @return
     * @throws NoSuchAlgorithmException 
     * @throws KeyStoreException 
     * @throws IOException 
     * @throws CertificateException 
     * @throws UnrecoverableKeyException 
     * @throws KeyManagementException 
     */
    public static SSLContext getSSLContext(
            FileInputStream trustFileInputStream, String trustPasswd,
            FileInputStream keyFileInputStream, String keyPasswd)
            throws NoSuchAlgorithmException, KeyStoreException,
            CertificateException, IOException, UnrecoverableKeyException,
            KeyManagementException {

        // ca
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);
        KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);
        trustKeyStore.load(trustFileInputStream, HttpClientUtil
                .str2CharArray(trustPasswd));
        tmf.init(trustKeyStore);

        final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);
        KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);
        ks.load(keyFileInputStream, kp);
        kmf.init(ks, kp);

        SecureRandom rand = new SecureRandom();
        SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);

        return ctx;
    }
    
    /**
     * 获取CA证书信息
     * @param cafile CA证书文件
     * @return Certificate
     * @throws CertificateException
     * @throws IOException
     */
    public static Certificate getCertificate(File cafile)
            throws CertificateException, IOException {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        FileInputStream in = new FileInputStream(cafile);
        Certificate cert = cf.generateCertificate(in);
        in.close();
        return cert;
    }
    
    /**
     * 字符串转换成char数组
     * @param str
     * @return char[]
     */
    public static char[] str2CharArray(String str) {
        if(null == str) return null;
        
        return str.toCharArray();
    }
    
    /**
     * 存储ca证书成JKS格式
     * @param cert
     * @param alias
     * @param password
     * @param out
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws CertificateException
     * @throws IOException
     */
    public static void storeCACert(Certificate cert, String alias,
            String password, OutputStream out) throws KeyStoreException,
            NoSuchAlgorithmException, CertificateException, IOException {
        KeyStore ks = KeyStore.getInstance("JKS");

        ks.load(null, null);

        ks.setCertificateEntry(alias, cert);

        // store keystore
        ks.store(out, HttpClientUtil.str2CharArray(password));

    }
    
    public static InputStream String2Inputstream(String str) {
        return new ByteArrayInputStream(str.getBytes());
    }
}
package com.j1.mai.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HttpRequestProxy
{
   
    private static int connectTimeOut = 10000;

 
    private static int readTimeOut = 10000;

  
    private static String requestEncoding = "UTF-8";

    public static String doGet(String reqUrl,String requestEncoding,String recvEncoding){
        HttpRequestProxy.requestEncoding = requestEncoding;
        return doGet(reqUrl,recvEncoding);
    }
    public static String doPost(String reqUrl, @SuppressWarnings("rawtypes") Map parameters,String requestEncoding, String recvEncoding){
        HttpRequestProxy.requestEncoding = requestEncoding;
        return doPost( reqUrl,parameters,recvEncoding);
    }
    @SuppressWarnings("rawtypes")
    public static String doGet(String reqUrl, Map parameters,
            String recvEncoding)
    {
        HttpURLConnection url_con = null;
        String responseContent = null;
        try
        {
            StringBuffer params = new StringBuffer();
            for (Iterator iter = parameters.entrySet().iterator(); iter
                    .hasNext();)
            {
                Entry element = (Entry) iter.next();
                params.append(element.getKey().toString());
                params.append("=");
                params.append(URLEncoder.encode(element.getValue().toString(),
                        HttpRequestProxy.requestEncoding));
                params.append("&");
            }

            if (params.length() > 0)
            {
                params = params.deleteCharAt(params.length() - 1);
            }

            URL url = new URL(reqUrl);
            url_con = (HttpURLConnection) url.openConnection();
            url_con.setRequestMethod("GET");
            System.setProperty("sun.net.client.defaultConnectTimeout", String
                    .valueOf(HttpRequestProxy.connectTimeOut));
            System.setProperty("sun.net.client.defaultReadTimeout", String
                    .valueOf(HttpRequestProxy.readTimeOut));
           
            url_con.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            url_con.getOutputStream().write(b, 0, b.length);
            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();

            InputStream in = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                    recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer temp = new StringBuffer();
            String crlf=System.getProperty("line.separator");
            while (tempLine != null)
            {
                temp.append(tempLine);
                temp.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = temp.toString();
            rd.close();
            in.close();
        }
        catch (IOException e)
        {

        }
        finally
        {
            if (url_con != null)
            {
                url_con.disconnect();
            }
        }

        return responseContent;
    }

    /**
   
     */
    public static String doGet(String reqUrl, String recvEncoding)
    {
        HttpURLConnection url_con = null;
        String responseContent = null;
        try
        {
            StringBuffer params = new StringBuffer();
            String queryUrl = reqUrl;
            int paramIndex = reqUrl.indexOf("?");

            if (paramIndex > 0)
            {
                queryUrl = reqUrl.substring(0, paramIndex);
                String parameters = reqUrl.substring(paramIndex + 1, reqUrl
                        .length());
                String[] paramArray = parameters.split("&");
                for (int i = 0; i < paramArray.length; i++)
                {
                    String string = paramArray[i];
                    int index = string.indexOf("=");
                    if (index > 0)
                    {
                        String parameter = string.substring(0, index);
                        String value = string.substring(index + 1, string
                                .length());
                        params.append(parameter);
                        params.append("=");
                        params.append(URLEncoder.encode(value,
                                HttpRequestProxy.requestEncoding));
                        params.append("&");
                    }
                }

                params = params.deleteCharAt(params.length() - 1);
            }

            URL url = new URL(queryUrl);
            url_con = (HttpURLConnection) url.openConnection();
            url_con.setRequestMethod("GET");
            System.setProperty("sun.net.client.defaultConnectTimeout", String
                    .valueOf(HttpRequestProxy.connectTimeOut));//
            System.setProperty("sun.net.client.defaultReadTimeout", String
                    .valueOf(HttpRequestProxy.readTimeOut)); // 
           
            url_con.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            url_con.getOutputStream().write(b, 0, b.length);
            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();
            InputStream in = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                    recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer temp = new StringBuffer();
            String crlf=System.getProperty("line.separator");
            while (tempLine != null)
            {
                temp.append(tempLine);
                temp.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = temp.toString();
            rd.close();
            in.close();
        }
        catch (IOException e)
        {

        }
        finally
        {
            if (url_con != null)
            {
                url_con.disconnect();
            }
        }

        return responseContent;
    }

    /**

     
     */
    public static String doPost(String reqUrl, @SuppressWarnings("rawtypes") Map parameters,
            String recvEncoding)
    {
        HttpURLConnection url_con = null;
        String responseContent = null;
        try
        {
            StringBuffer params = new StringBuffer();
            for (@SuppressWarnings("rawtypes")
            Iterator iter = parameters.entrySet().iterator(); iter
                    .hasNext();)
            {
                @SuppressWarnings("rawtypes")
                Entry element = (Entry) iter.next();
                params.append(element.getKey().toString());
                params.append("=");
                params.append(URLEncoder.encode(element.getValue().toString(),
                        HttpRequestProxy.requestEncoding));
                params.append("&");
            }

            if (params.length() > 0)
            {
                params = params.deleteCharAt(params.length() - 1);
            }

            URL url = new URL(reqUrl);
            url_con = (HttpURLConnection) url.openConnection();
            url_con.setRequestMethod("POST");
            System.setProperty("sun.net.client.defaultConnectTimeout", String
                    .valueOf(10000000));
            System.setProperty("sun.net.client.defaultReadTimeout", String
                    .valueOf(10000000)); 
          
            url_con.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            url_con.getOutputStream().write(b, 0, b.length);
            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();

            InputStream in = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                    recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer tempStr = new StringBuffer();
            String crlf=System.getProperty("line.separator");
            while (tempLine != null)
            {
                tempStr.append(tempLine);
                tempStr.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = tempStr.toString();
            rd.close();
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (url_con != null)
            {
                url_con.disconnect();
            }
        }
        return responseContent;
    }

    /**
  
     */
    public static int getConnectTimeOut()
    {
        return HttpRequestProxy.connectTimeOut;
    }

    /**
     
     */
    public static int getReadTimeOut()
    {
        return HttpRequestProxy.readTimeOut;
    }

    /**
     
     */
    public static String getRequestEncoding()
    {
        return requestEncoding;
    }

    /**
  
     */
    public static void setConnectTimeOut(int connectTimeOut)
    {
        HttpRequestProxy.connectTimeOut = connectTimeOut;
    }

    /**
   
     */
    public static void setReadTimeOut(int readTimeOut)
    {
        HttpRequestProxy.readTimeOut = readTimeOut;
    }

  
    public static void setRequestEncoding(String requestEncoding)
    {
        HttpRequestProxy.requestEncoding = requestEncoding;
    }
}
package com.founder.ec.cps.cps360;
import java.io.DataInputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

public class HttpPost {
    public String send(String method, String strurl, HashMap<String, String> data) throws Exception{
        StringBuilder content = new StringBuilder();
        Iterator<String> iter = data.keySet().iterator();
        while(iter.hasNext()){
            if(content.length() != 0) content.append("&");
            String key = iter.next();
            content.append(key + "=" + URLEncoder.encode( data.get(key), "UTF-8"));
        }
        return this.send(method, strurl, content.toString());
    }
    public String send(String method, String strurl, ArrayList<String> data) throws Exception{
        StringBuilder content = new StringBuilder();
        for(String one : data){
            if(content.length() != 0) content.append("&");
            content.append(URLEncoder.encode(one, "UTF-8"));
        }
        return this.send(method, strurl, content.toString());
    }
    public String send(String method, String strurl, String content){
        HttpURLConnection con = null;
        if(method == null || method.isEmpty()) method = "GET";
        String retValue = null;
        URL url = null;
        try {
            url = new URL(strurl);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod(method);
            con.setDoInput(true);
            con.setDoOutput(true);
            PrintWriter out = new PrintWriter(con.getOutputStream());
            out.println(content);
            out.flush();
            DataInputStream bin = new DataInputStream(con.getInputStream());
            StringBuffer buff = new StringBuffer();
            byte[] b = new byte[4096];
            int start = 0, len = 0;
            while ( (len=bin.read(b, start, 4096)) > 0) {
                b[len] = 0;
                buff.append(b);
            }
            retValue = buff.toString();
            out.close();
            bin.close();
            con.disconnect();
        }
        catch (Exception e) {
            return e.getMessage();
        }
        return retValue;
    }
    public String getIpAddrByRequest(HttpServletRequest request) {  
        String ip = request.getHeader("x-forwarded-for");  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }  
        return ip;  
    } 

}
package com.founder.ec.web.webService.alipay.util.httpClient;

import java.io.IOException;
import java.net.UnknownHostException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.util.IdleConnectionTimeoutThread;

/* *
 *类名:HttpProtocolHandler
 *功能:HttpClient方式访问
 *详细:获取远程HTTP数据
 *版本:3.2
 *日期:2011-03-17
 *说明:
 *以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
 *该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
 */

public class HttpProtocolHandler {

    private static String              DEFAULT_CHARSET                     = "GBK";

    /** 连接超时时间,由bean factory设置,缺省为8秒钟 */
    private int                        defaultConnectionTimeout            = 8000;

    /** 回应超时时间, 由bean factory设置,缺省为30秒钟 */
    private int                        defaultSoTimeout                    = 30000;

    /** 闲置连接超时时间, 由bean factory设置,缺省为60秒钟 */
    private int                        defaultIdleConnTimeout              = 60000;

    private int                        defaultMaxConnPerHost               = 30;

    private int                        defaultMaxTotalConn                 = 80;

    /** 默认等待HttpConnectionManager返回连接超时(只有在达到最大连接数时起作用):1秒*/
    private static final long          defaultHttpConnectionManagerTimeout = 3 * 1000;

    /**
     * HTTP连接管理器,该连接管理器必须是线程安全的.
     */
    private HttpConnectionManager      connectionManager;

    private static HttpProtocolHandler httpProtocolHandler                 = new HttpProtocolHandler();

    /**
     * 工厂方法
     * 
     * @return
     */
    public static HttpProtocolHandler getInstance() {
        return httpProtocolHandler;
    }

    /**
     * 私有的构造方法
     */
    private HttpProtocolHandler() {
        // 创建一个线程安全的HTTP连接池
        connectionManager = new MultiThreadedHttpConnectionManager();
        connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost);
        connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn);

        IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread();
        ict.addConnectionManager(connectionManager);
        ict.setConnectionTimeout(defaultIdleConnTimeout);

        ict.start();
    }

    /**
     * 执行Http请求
     * 
     * @param request
     * @return
     */
    public HttpResponse execute(HttpRequest request) {
        HttpClient httpclient = new HttpClient(connectionManager);

        // 设置连接超时
        int connectionTimeout = defaultConnectionTimeout;
        if (request.getConnectionTimeout() > 0) {
            connectionTimeout = request.getConnectionTimeout();
        }
        httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

        // 设置回应超时
        int soTimeout = defaultSoTimeout;
        if (request.getTimeout() > 0) {
            soTimeout = request.getTimeout();
        }
        httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);

        // 设置等待ConnectionManager释放connection的时间
        httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);

        String charset = request.getCharset();
        charset = charset == null ? DEFAULT_CHARSET : charset;
        HttpMethod method = null;

        if (request.getMethod().equals(HttpRequest.METHOD_GET)) {
            method = new GetMethod(request.getUrl());
            method.getParams().setCredentialCharset(charset);

            // parseNotifyConfig会保证使用GET方法时,request一定使用QueryString
            method.setQueryString(request.getQueryString());
        } else {
            method = new PostMethod(request.getUrl());
            ((PostMethod) method).addParameters(request.getParameters());
            method.addRequestHeader("Content-Type",
                "application/x-www-form-urlencoded; text/html; charset=" + charset);

        }

        // 设置Http Header中的User-Agent属性
        method.addRequestHeader("User-Agent", "Mozilla/4.0");
        HttpResponse response = new HttpResponse();

        try {
            httpclient.executeMethod(method);
            if (request.getResultType().equals(HttpResultType.STRING)) {
                response.setStringResult(method.getResponseBodyAsString());
            } else if (request.getResultType().equals(HttpResultType.BYTES)) {
                response.setByteResult(method.getResponseBody());
            }
            response.setResponseHeaders(method.getResponseHeaders());
        } catch (UnknownHostException ex) {

            return null;
        } catch (IOException ex) {

            return null;
        } catch (Exception ex) {

            return null;
        } finally {
            method.releaseConnection();
        }
        return response;
    }

    /**
     * 将NameValuePairs数组转变为字符串
     * 
     * @param nameValues
     * @return
     */
    protected String toString(NameValuePair[] nameValues) {
        if (nameValues == null || nameValues.length == 0) {
            return "null";
        }

        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < nameValues.length; i++) {
            NameValuePair nameValue = nameValues[i];

            if (i == 0) {
                buffer.append(nameValue.getName() + "=" + nameValue.getValue());
            } else {
                buffer.append("&" + nameValue.getName() + "=" + nameValue.getValue());
            }
        }

        return buffer.toString();
    }
}
package com.founder.ec.web.webService.alipay.util.httpClient;

import org.apache.commons.httpclient.NameValuePair;

/* *
 *类名:HttpRequest
 *功能:Http请求对象的封装
 *详细:封装Http请求
 *版本:3.2
 *日期:2011-03-17
 *说明:
 *以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
 *该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
 */

public class HttpRequest {

    /** HTTP GET method */
    public static final String METHOD_GET        = "GET";

    /** HTTP POST method */
    public static final String METHOD_POST       = "POST";

    /**
     * 待请求的url
     */
    private String             url               = null;

    /**
     * 默认的请求方式
     */
    private String             method            = METHOD_POST;

    private int                timeout           = 0;

    private int                connectionTimeout = 0;

    /**
     * Post方式请求时组装好的参数值对
     */
    private NameValuePair[]    parameters        = null;

    /**
     * Get方式请求时对应的参数
     */
    private String             queryString       = null;

    /**
     * 默认的请求编码方式
     */
    private String             charset           = "GBK";

    /**
     * 请求发起方的ip地址
     */
    private String             clientIp;

    /**
     * 请求返回的方式
     */
    private HttpResultType     resultType        = HttpResultType.BYTES;

    public HttpRequest(HttpResultType resultType) {
        super();
        this.resultType = resultType;
    }

    /**
     * @return Returns the clientIp.
     */
    public String getClientIp() {
        return clientIp;
    }

    /**
     * @param clientIp The clientIp to set.
     */
    public void setClientIp(String clientIp) {
        this.clientIp = clientIp;
    }

    public NameValuePair[] getParameters() {
        return parameters;
    }

    public void setParameters(NameValuePair[] parameters) {
        this.parameters = parameters;
    }

    public String getQueryString() {
        return queryString;
    }

    public void setQueryString(String queryString) {
        this.queryString = queryString;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public int getConnectionTimeout() {
        return connectionTimeout;
    }

    public void setConnectionTimeout(int connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    /**
     * @return Returns the charset.
     */
    public String getCharset() {
        return charset;
    }

    /**
     * @param charset The charset to set.
     */
    public void setCharset(String charset) {
        this.charset = charset;
    }

    public HttpResultType getResultType() {
        return resultType;
    }

    public void setResultType(HttpResultType resultType) {
        this.resultType = resultType;
    }

}
package com.j1.mai.util;


import java.io.IOException;
import java.util.Map;
import java.util.Set;

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.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;


public class HttpUtils {
    /**
     * 发送HTTP请求
     *
     * @param url
     * @param propsMap 发送的参数
     */
    public static HttpResponse httpPost(String url, Map<String, Object> propsMap) {
        HttpResponse response = new HttpResponse();
        String responseMsg = "";

        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);// POST请求
        if (propsMap != null) {
            // 参数设置
            Set<String> keySet = propsMap.keySet();
            NameValuePair[] postData = new NameValuePair[keySet.size()];
            int index = 0;
            for (String key : keySet) {
                postData[index++] = new NameValuePair(key, propsMap.get(key)
                        .toString());
            }
            postMethod.addParameters(postData);
        }
        postMethod.getParams().setParameter(
                HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        try {
            int statusCode = httpClient.executeMethod(postMethod);// 发送请求
            response.setStatusCode(statusCode);
            if (statusCode == HttpStatus.SC_OK) {
                // 读取内容
                byte[] responseBody = postMethod.getResponseBody();
                // 处理返回的内容
                responseMsg = new String(responseBody, "utf-8");
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();// 关闭连接
        }
        response.setContent(responseMsg);
        return response;
    }

    /**
     * 发送HTTP请求
     *
     * @param url
     */
    public static HttpResponse httpGet(String url) {
        HttpResponse response = new HttpResponse();
        String responseMsg = "";

        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);

        try {
            int statusCode = httpClient.executeMethod(getMethod);// 发送请求
            response.setStatusCode(statusCode);
            if (statusCode == HttpStatus.SC_OK) {
                // 读取内容
                byte[] responseBody = getMethod.getResponseBody();
                // 处理返回的内容
                responseMsg = new String(responseBody, "utf-8");
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();// 关闭连接
        }
        response.setContent(responseMsg);
        return response;
    }
    
    /**
     * 发送HTTP--GET请求
     * 
     * @param url
     * @param propsMap
     *            发送的参数
     */
    public static String httpGetSend(String url) {
        String responseMsg = "";
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);// GET请求
        try {
            // http超时5秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            // 设置 get 请求超时为 5 秒
            getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
            httpClient.executeMethod(getMethod);// 发送请求
            // 读取内容
            byte[] responseBody = getMethod.getResponseBody();
            // 处理返回的内容
            responseMsg = new String(responseBody, "utf-8");
        } catch (Exception e) {
            Logger.getLogger(HttpUtils.class).error(e.getMessage());
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();// 关闭连接
        }
        return responseMsg;
    }
    
    
    /**
     * 发送HTTP请求
     * 
     * @param url
     * @param propsMap
     *            发送的参数
     */
    public static String httpSend(String url, Map<String, Object> propsMap) {
        String responseMsg = "";

        HttpClient httpClient = new HttpClient();
        
        PostMethod postMethod = new PostMethod(url);// POST请求
        
//        postMethod.
        // 参数设置
        Set<String> keySet = propsMap.keySet();
        NameValuePair[] postData = new NameValuePair[keySet.size()];
        int index = 0;
        for (String key : keySet) {
            postData[index++] = new NameValuePair(key, propsMap.get(key)
                    .toString());
        }
        postMethod.addParameters(postData);
        try {
            httpClient.executeMethod(postMethod);// 发送请求
//            Log.info(postMethod.getStatusCode());
            // 读取内容
            byte[] responseBody = postMethod.getResponseBody();
            // 处理返回的内容
            responseMsg = new String(responseBody);

        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();// 关闭连接
        }
        return responseMsg;
    }
    
    
    /**
     * 发送Post HTTP请求
     * 
     * @param url
     * @param propsMap
     *            发送的参数
     * @throws IOException 
     * @throws HttpException 
     */
    public static PostMethod httpSendPost(String url, Map<String, Object> propsMap,String authrition) throws Exception {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);// POST请求
        postMethod.addRequestHeader("Authorization",authrition);
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");  
        // 参数设置
        Set<String> keySet = propsMap.keySet();
        NameValuePair[] postData = new NameValuePair[keySet.size()];
        int index = 0;
        for (String key : keySet) {
            postData[index++] = new NameValuePair(key, propsMap.get(key)
                    .toString());
        }
        postMethod.addParameters(postData);
        
        httpClient.executeMethod(postMethod);// 发送请求
        return postMethod;
    }
    
    /**
     * 发送Post HTTP请求
     * 
     * @param url
     * @param propsMap
     *            发送的参数
     * @throws IOException 
     * @throws HttpException 
     */
    public static PostMethod httpSendPost(String url, Map<String, Object> propsMap) throws Exception {
        String responseMsg = "";
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);// POST请求
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");  
        // 参数设置
        Set<String> keySet = propsMap.keySet();
        NameValuePair[] postData = new NameValuePair[keySet.size()];
        int index = 0;
        for (String key : keySet) {
            postData[index++] = new NameValuePair(key, propsMap.get(key)
                    .toString());
        }
        postMethod.addParameters(postData);
        
        httpClient.executeMethod(postMethod);// 发送请求
        return postMethod;
    }
    
    
    /**
     * 发送Get HTTP请求
     * 
     * @param url
     * @param propsMap
     *            发送的参数
     * @throws IOException 
     * @throws HttpException 
     */
    public static GetMethod httpSendGet(String url, Map<String, Object> propsMap) throws Exception {
        String responseMsg = "";
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);// GET请求
        getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");  
        // 参数设置
        Set<String> keySet = propsMap.keySet();
        NameValuePair[] postData = new NameValuePair[keySet.size()];
        int index = 0;
        for (String key : keySet) {
            getMethod.getParams().setParameter(key, propsMap.get(key)
                    .toString());
        }
        
        httpClient.executeMethod(getMethod);// 发送请求
        return getMethod;
    }
    
}
package com.j1.weixin.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HttpRequestProxy
{
   
    private static int connectTimeOut = 10000;

 
    private static int readTimeOut = 10000;

  
    private static String requestEncoding = "UTF-8";

    public static String doGet(String reqUrl,String requestEncoding,String recvEncoding){
        HttpRequestProxy.requestEncoding = requestEncoding;
        return doGet(reqUrl,recvEncoding);
    }
    public static String doPost(String reqUrl, @SuppressWarnings("rawtypes") Map parameters,String requestEncoding, String recvEncoding){
        HttpRequestProxy.requestEncoding = requestEncoding;
        return doPost( reqUrl,parameters,recvEncoding);
    }
    @SuppressWarnings("rawtypes")
    public static String doGet(String reqUrl, Map parameters,
            String recvEncoding)
    {
        HttpURLConnection url_con = null;
        String responseContent = null;
        try
        {
            StringBuffer params = new StringBuffer();
            for (Iterator iter = parameters.entrySet().iterator(); iter
                    .hasNext();)
            {
                Entry element = (Entry) iter.next();
                params.append(element.getKey().toString());
                params.append("=");
                params.append(URLEncoder.encode(element.getValue().toString(),
                        HttpRequestProxy.requestEncoding));
                params.append("&");
            }

            if (params.length() > 0)
            {
                params = params.deleteCharAt(params.length() - 1);
            }

            URL url = new URL(reqUrl);
            url_con = (HttpURLConnection) url.openConnection();
            url_con.setRequestMethod("GET");
            System.setProperty("sun.net.client.defaultConnectTimeout", String
                    .valueOf(HttpRequestProxy.connectTimeOut));
            System.setProperty("sun.net.client.defaultReadTimeout", String
                    .valueOf(HttpRequestProxy.readTimeOut));
           
            url_con.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            url_con.getOutputStream().write(b, 0, b.length);
            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();

            InputStream in = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                    recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer temp = new StringBuffer();
            String crlf=System.getProperty("line.separator");
            while (tempLine != null)
            {
                temp.append(tempLine);
                temp.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = temp.toString();
            rd.close();
            in.close();
        }
        catch (IOException e)
        {

        }
        finally
        {
            if (url_con != null)
            {
                url_con.disconnect();
            }
        }

        return responseContent;
    }

    /**
   
     */
    public static String doGet(String reqUrl, String recvEncoding)
    {
        HttpURLConnection url_con = null;
        String responseContent = null;
        try
        {
            StringBuffer params = new StringBuffer();
            String queryUrl = reqUrl;
            int paramIndex = reqUrl.indexOf("?");

            if (paramIndex > 0)
            {
                queryUrl = reqUrl.substring(0, paramIndex);
                String parameters = reqUrl.substring(paramIndex + 1, reqUrl
                        .length());
                String[] paramArray = parameters.split("&");
                for (int i = 0; i < paramArray.length; i++)
                {
                    String string = paramArray[i];
                    int index = string.indexOf("=");
                    if (index > 0)
                    {
                        String parameter = string.substring(0, index);
                        String value = string.substring(index + 1, string
                                .length());
                        params.append(parameter);
                        params.append("=");
                        params.append(URLEncoder.encode(value,
                                HttpRequestProxy.requestEncoding));
                        params.append("&");
                    }
                }

                params = params.deleteCharAt(params.length() - 1);
            }

            URL url = new URL(queryUrl);
            url_con = (HttpURLConnection) url.openConnection();
            url_con.setRequestMethod("GET");
            System.setProperty("sun.net.client.defaultConnectTimeout", String
                    .valueOf(HttpRequestProxy.connectTimeOut));//
            System.setProperty("sun.net.client.defaultReadTimeout", String
                    .valueOf(HttpRequestProxy.readTimeOut)); // 
           
            url_con.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            url_con.getOutputStream().write(b, 0, b.length);
            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();
            InputStream in = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                    recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer temp = new StringBuffer();
            String crlf=System.getProperty("line.separator");
            while (tempLine != null)
            {
                temp.append(tempLine);
                temp.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = temp.toString();
            rd.close();
            in.close();
        }
        catch (IOException e)
        {

        }
        finally
        {
            if (url_con != null)
            {
                url_con.disconnect();
            }
        }

        return responseContent;
    }

    /**

     
     */
    public static String doPost(String reqUrl, @SuppressWarnings("rawtypes") Map parameters,
            String recvEncoding)
    {
        HttpURLConnection url_con = null;
        String responseContent = null;
        try
        {
            StringBuffer params = new StringBuffer();
            for (@SuppressWarnings("rawtypes")
            Iterator iter = parameters.entrySet().iterator(); iter
                    .hasNext();)
            {
                @SuppressWarnings("rawtypes")
                Entry element = (Entry) iter.next();
                params.append(element.getKey().toString());
                params.append("=");
                params.append(URLEncoder.encode(element.getValue().toString(),
                        HttpRequestProxy.requestEncoding));
                params.append("&");
            }

            if (params.length() > 0)
            {
                params = params.deleteCharAt(params.length() - 1);
            }

            URL url = new URL(reqUrl);
            url_con = (HttpURLConnection) url.openConnection();
            url_con.setRequestMethod("POST");
            System.setProperty("sun.net.client.defaultConnectTimeout", String
                    .valueOf(10000000));
            System.setProperty("sun.net.client.defaultReadTimeout", String
                    .valueOf(10000000)); 
          
            url_con.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            url_con.getOutputStream().write(b, 0, b.length);
            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();

            InputStream in = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                    recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer tempStr = new StringBuffer();
            String crlf=System.getProperty("line.separator");
            while (tempLine != null)
            {
                tempStr.append(tempLine);
                tempStr.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = tempStr.toString();
            rd.close();
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (url_con != null)
            {
                url_con.disconnect();
            }
        }
        return responseContent;
    }

    /**
  
     */
    public static int getConnectTimeOut()
    {
        return HttpRequestProxy.connectTimeOut;
    }

    /**
     
     */
    public static int getReadTimeOut()
    {
        return HttpRequestProxy.readTimeOut;
    }

    /**
     
     */
    public static String getRequestEncoding()
    {
        return requestEncoding;
    }

    /**
  
     */
    public static void setConnectTimeOut(int connectTimeOut)
    {
        HttpRequestProxy.connectTimeOut = connectTimeOut;
    }

    /**
   
     */
    public static void setReadTimeOut(int readTimeOut)
    {
        HttpRequestProxy.readTimeOut = readTimeOut;
    }

  
    public static void setRequestEncoding(String requestEncoding)
    {
        HttpRequestProxy.requestEncoding = requestEncoding;
    }
}
package com.j1.soa.resource.member.oracle.service;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;

import com.j1.soa.common.Md5Util;
  

    
public class HttpText {


     final static String url = "http://192.168.200.53:8081/httpServer/c_i/common_i";
    //final static String url = "http://127.0.0.1:8080/httpServer/c_i/common_i";
      
    /**
     * 发送HttpPost请求
     * @param strURL  服务地址
     * @param sign  加密后的32 大写 MD5
     * @return 成功:返回json字符串<br/>
     */
    public static String post(String strURL,  String format,String method ,String sessionKey,String up_Date,String version,String sign) {
        System.out.println(strURL);
        System.out.println(sign);
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
             connection.setDoOutput(true); 
             connection.setDoInput(true); 
             connection.setRequestMethod("POST"); 
             connection.setUseCaches(false); 
             connection.setInstanceFollowRedirects(true); 
           //  connection.setContentType("text/xml;charset=utf-8");
             connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式  
             connection.setRequestProperty("ContentType", "utf-8"); // 设置发送数据的格式  
             connection.setRequestProperty("Accept-Charset", "utf-8"); 
             connection.connect(); 
               //POST请求 
          //   BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));  
             PrintWriter out =   new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"utf-8")); // utf-8编码  ; 
            JSONObject obj = new JSONObject(); 
            obj.element("sessionKey", sessionKey); 
            obj.element("method",method); 
            obj.element("format", format); 
            obj.element("up_Date", up_Date); 
            obj.element("sign", sign); 
            obj.element("version", version);
           JSONObject objbusinessdate = new JSONObject(); 
           objbusinessdate.element("memCardNo", "f999999299-ffJ1");//卡号
            objbusinessdate.element("contactor", "移动人");//姓名
             objbusinessdate.element("idCardCode", "32080220163212012");//身份证
           objbusinessdate.element("sex", "F");//性别
           objbusinessdate.element("birthDay", "2016-03-21");//生日 YYYY-MM-DD
        //    objbusinessdate.element("age",  19);//年龄
             objbusinessdate.element("address", "移动电话");// 地址
        //    objbusinessdate.element("hTel", "1111111111");// 座机
             objbusinessdate.element("mTel", "00800780");// 移动电话
           objbusinessdate.element("eMail", "11111@j1.com");//email
           objbusinessdate.element("enrDeptId", "1111");//部门id
             objbusinessdate.element("roptrId", "3219");//操作人id
            objbusinessdate.element("ybCardCode", "111111111111");//医保卡
         //   objbusinessdate.element("qqCode", "111111");//qq
            objbusinessdate.element("note", "移动电话"); //备注 
            //"contactor":"15821023367","sex":"1","mTel":"15821023367","eMail":"fufu_pupu@163.com","regTime":"2016-11-22 10:18:19"
           /*** JSONObject objbusinessdate = new JSONObject(); 
                       objbusinessdate.element("username", "tyf");//  username ,
                       objbusinessdate.element("password", "1111"); //password
                       
                       /***
                        * select    te.tranid     tranId,
                                    ca.contactor  contactor ,
                                    ca.memcardno  memCardNo,
                                     sa.retnamt   discount,
                                    sa.saleamt     saleAmt ,
                                    sa.trandate    tranDate,
                                    cae.articode   artiCode,
                                    cae.artiname   artiName,
                                    -te.artiqty    artiQty ,
                                    te.saleprice   salePrice
                                    
                 JSONObject objbusinessdate = new JSONObject(); 
                        objbusinessdate.element("deptNo", "000");//门店编码
                        objbusinessdate.element("deptName", "000");//门店名称
                        objbusinessdate.element("tranid", "1123");//  销售订单号 ,
                        objbusinessdate.element("contactor", "000");// 会员名称
                        objbusinessdate.element("memCardNo", "000");//会员卡号
                        objbusinessdate.element("discount", "000");//优惠
                        objbusinessdate.element("mTel", "000");//手机号码
                JSONObject artiitem = new JSONObject();         
                        
                        artiitem.element("saleAmt", "000");//实付金额
                        artiitem.element("tranDate", "000");//销售时间
                        artiitem.element("artiCode", "000");      //商品编码
                        artiitem.element("artiName", "000");//商品名称
                        artiitem.element("artiQty", "000");//数量
                        artiitem.element("salePrice", "000");  //成交价格    
                 objbusinessdate.element("artiitem", artiitem);        
                        */
          //  String txt = new String(objbusinessdate.toString().getBytes(), "utf-8"); 
            obj.element("businessData", objbusinessdate);
             
            System.out.println(obj.toString());
            
           // out.write(obj.toString().getBytes());
             
            // 发送请求参数
            out.print(obj.toString() );
            // flush输出流的缓冲
            out.flush();
            
            // 读取响应
            int length = (int) connection.getContentLength();// 获取长度
            System.out.println("length:"+length);
            BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while( (line = rd.readLine())!=null){
                buffer.append(line);
            }
            out.close();
            rd.close(); 

            connection.disconnect();
            System.out.println(buffer.toString()+"  0000");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }

    public static void main(String[] args) {
        
        //MD5加密顺序  format  meThod  sessionKey token  up_date  version
        //           format+method+sessionKey+token+up_date+version
         String token="91A1643059824847938125BA0AC0F557";//"bf0d8da2736e4d8caea055d863610a33  ";91A1643059824847938125BA0AC0F557 //token 不产于传送 但是参与加密
                       
         String format ="json";      //传送方式
         String method ="saveMember";//"queryTbl_Employee " erpTranDetailCount_ToJ1 saveMember ;//调用方法
         String sessionKey ="123456789078945";//sessionkey
         String up_date ="2016-10-27";//上传日期  yyyy-mm-dd
         String version ="1.0.2";//版本号
         
             
     
     //  TranIdListServiceImpl.testhttprequest();
         //System.exit(0);
         String sign=null;
        try {
            sign = Md5Util.Bit32(format+method+sessionKey +token+up_date+version);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          post(url,format,method ,sessionKey,up_date,version,sign);
    }
 
 
}
package com.founder.ec.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.httpclient.HttpException;

public class HttpSenderUtil {

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
    
    public static  String httpSend(String url, Map<String, Object> propsMap)  throws Exception{
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);// POST请求
        String returnString ="";
        // 参数设置
        Set<String> keySet = propsMap.keySet();
        NameValuePair[] postData = new NameValuePair[keySet.size()];
        int index = 0;
        for (String key : keySet) {
            postData[index++] = new NameValuePair(key, propsMap.get(key).toString());
        }
        postMethod.addParameters(postData);
        try {
            httpClient.executeMethod(postMethod);// 发送请求
            java.io.InputStream input = postMethod.getResponseBodyAsStream();
            returnString = convertStreamToString(input).toString();

        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();// 关闭连接
        }
        return returnString;
    }

    public static String convertStreamToString(java.io.InputStream input)
            throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input,
                "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        input.close();
        return sb.toString();
    }
    
    
    public static void main(String[] strs){
        long time=new Date().getTime();
        String check=MD5.getMD5(time+"www.j1.com");
        String mobile="13053702096";
        String msg="尊敬的用户  , 您在健一网的安全验证码为897489,健一网祝您身体健康";
        String param="t="+time+"&mobile="+mobile+"&msg="+msg+"&check="+check;
        String res=HttpSenderUtil.sendPost("http://localhost:8080/ec-dec/page/sms/sendSms/code",param);
        System.out.println(res);
    }
    /**
     * 执行get方法
     * @param url
     * @param queryString
     * @return
     */
    public static String doGet(String url, String queryString) { 
        String response = null;
        HttpClient client = new HttpClient(); 
        HttpMethod method = new GetMethod(url); 
        try { 
                if (StringUtils.isNotBlank(queryString)) 
                        method.setQueryString(URIUtil.encodeQuery(queryString)); 
                client.executeMethod(method); 
                if (method.getStatusCode() == HttpStatus.SC_OK) { 
                        response = method.getResponseBodyAsString(); 
                } 
        } catch (URIException e) { 
            //logger.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e); 
        } catch (IOException e) { 
            //logger.error("执行HTTP Get请求" + url + "时,发生异常!", e); 
        } finally { 
            method.releaseConnection(); 
        }
        return response; 
    }

}
package com.founder.ec.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import com.founder.ec.common.utils.MD5;

public class HttpSenderUtil {

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url 发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] strs) {
        /** 发送内容 */
        long time = new Date().getTime();
        String check = MD5.getMD5(time + "www.j1.com");
        String mobile = ""; // 填写接收人短信的手机号(默认自己)
        String msg = "尊敬的用户 ,您在健一网的安全验证码为897489,健一网祝您身体健康。";
        String param = "t=" + time + "&mobile=" + mobile + "&msg=" + msg + "&check=" + check;

        /** 发送地址 */
        String res = HttpSenderUtil.sendPost("http://adm.j1.com/ec-dec/page/sms/sendSms/notice", param); // 真实地址

        /** 解析返回结果 */
        // System.out.println(res);
        // String res = "{\"code\":0,\"msg\":\"发送成功\"}"; //测试
        // String res = "{\"code\":-1,\"msg\":\"非法的时间或者超时\"}"; //测试

        JSONObject jsonObj = (JSONObject) JSONValue.parse(res);
        System.out.println(jsonObj);

        Long codeStr = (Long) jsonObj.get("code");
        System.out.println(codeStr);

        String msgStr = (String) jsonObj.get("msg");
        System.out.println(msgStr);

    }

    public static String httpSend(String url, Map<String, Object> propsMap) throws Exception {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);// POST请求
        String returnString = "";
        // 参数设置
        Set<String> keySet = propsMap.keySet();
        NameValuePair[] postData = new NameValuePair[keySet.size()];
        int index = 0;
        for (String key : keySet) {
            postData[index++] = new NameValuePair(key, propsMap.get(key).toString());
        }
        postMethod.addParameters(postData);
        try {
            httpClient.executeMethod(postMethod);// 发送请求
            java.io.InputStream input = postMethod.getResponseBodyAsStream();
            returnString = convertStreamToString(input).toString();

        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();// 关闭连接
        }
        return returnString;
    }

    public static String convertStreamToString(java.io.InputStream input) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        input.close();
        return sb.toString();
    }
}

 

http

标签:this   3.2   doget   https   post请求   管理   nts   port   imp   

原文地址:http://www.cnblogs.com/wangchuanfu/p/6122467.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!