httpPost

package com.kkfun.cocoa.mahjong.utils;html


import java.io.BufferedReader;java

import java.io.ByteArrayOutputStream;算法

import java.io.IOException;apache

import java.io.InputStream;數組

import java.io.InputStreamReader;服務器

import java.io.PrintWriter;session

import java.io.UnsupportedEncodingException;app

import java.net.HttpURLConnection;post

import java.net.MalformedURLException;ui

import java.net.URL;

import java.net.URLConnection;

import java.net.URLEncoder;

import java.util.HashMap;

import java.util.Iterator;


import javax.crypto.Mac;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;


import org.apache.log4j.Logger;



public class HttpUtil

{


private static Logger log = Logger.getLogger(HttpUtil.class); 

private static final String MAC_NAME = "HmacSHA1";

private static final String ENCODING = "UTF-8";

/**

* http請求(get方式)

* @param url

* @param data

* @return

* @throws IOException 

*/

public static String requestUrl(String url, HashMap<String, String> data)

throws Exception {


// HttpURLConnection conn = null;

InputStreamReader streamReader = null;

BufferedReader bufferedReader;

StringBuilder sb = null;

String line;

try

{

// if GET....

// URL requestUrl = new URL(url + "?" + httpBuildQuery(data));

URL requestUrl = new URL(url);

HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();


conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");


conn.setConnectTimeout(5000);//鏈接服務器5s超時

//post請求

conn.setDoInput(true);

conn.setDoOutput(true);

conn.setRequestMethod("POST"); 

conn.connect();

PrintWriter writer = new PrintWriter(conn.getOutputStream());

// System.out.println(url+"?" +httpBuildQuery(data));

writer.print(httpBuildQuery(data));

writer.flush();

writer.close();


streamReader = new InputStreamReader(conn.getInputStream(), "UTF-8");

} catch (Exception e) {


// streamReader = new InputStreamReader(conn.getErrorStream(), "UTF-8");

log.error("requestUrl err", e);

e.printStackTrace();

} finally {

if (streamReader != null) {

bufferedReader = new BufferedReader(streamReader);

sb = new StringBuilder();

while ((line = bufferedReader.readLine()) != null) {

sb.append(line);

}

}

}

if (sb != null)

{

return sb.toString();

}

return null;

}

/**

     * 向指定 URL 發送POST方法的請求

     * 

     * @param url

     *            發送請求的 URL

     * @param param

     *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。

     * @return 所表明遠程資源的響應結果

     */

    public static String sendPost(String url, HashMap<String, String> data) {

        PrintWriter out = null;

        BufferedReader in = null;

        String result = "";

        try {

//            URL realUrl = new URL(url);

//            // 打開和URL之間的鏈接

//            URLConnection conn = realUrl.openConnection();

            

            URL requestUrl = new URL(url);

HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();

            // 設置通用的請求屬性

conn.setConnectTimeout(5000);//鏈接服務器5s超時

            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            

            // 發送POST請求必須設置以下兩行

            conn.setDoOutput(true);//向httpbody輸入數據,POST必須

            conn.setDoInput(true);//獲取輸出流,默認true

conn.setRequestMethod("POST"); 

conn.connect();

            // 獲取全部響應頭字段

//            Map<String, List<String>> map = conn.getHeaderFields();

//            // 遍歷全部的響應頭字段

//            for (String key : map.keySet()) {

//                System.out.println(key + "--->" + map.get(key));

//                log.info(key + "--->" + map.get(key));

//            }

            out = new PrintWriter(conn.getOutputStream());

            // 發送請求參數

            out.print(httpQuery(data));

            // 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);

            log.error("發送 POST 請求出現異常!"+e);

            e.printStackTrace();

        }

        //使用finally塊來關閉輸出流、輸入流

        finally{

            try{

                if(out!=null){

                    out.close();

                }

                if(in!=null){

                    in.close();

                }

            }

            catch(IOException ex){

                ex.printStackTrace();

            }

        }

        return result;

    } 

    /**

     * 向指定 URL 發送POST方法的請求

     * 

     * @param url

     *            發送請求的 URL

     * @param param

     *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。

     * @return 所表明遠程資源的響應結果

     */

    public static String sendPost(String url, String data) {

    PrintWriter out = null;

    BufferedReader in = null;

    String result = "";

    try {

//            URL realUrl = new URL(url);

//            // 打開和URL之間的鏈接

//            URLConnection conn = realUrl.openConnection();

   

    URL requestUrl = new URL(url);

    HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();

    // 設置通用的請求屬性

    conn.setConnectTimeout(5000);//鏈接服務器5s超時

//     conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.setRequestProperty("Content-Type", "text/html;charset=UTF-8");

   

    // 發送POST請求必須設置以下兩行

    conn.setDoOutput(true);//向httpbody輸入數據,POST必須

    conn.setDoInput(true);//獲取輸出流,默認true

    conn.setRequestMethod("POST"); 

    conn.connect();

   

    // 獲取全部響應頭字段

//            Map<String, List<String>> map = conn.getHeaderFields();

//            // 遍歷全部的響應頭字段

//            for (String key : map.keySet()) {

//                System.out.println(key + "--->" + map.get(key));

//                log.info(key + "--->" + map.get(key));

//            }

   

    out = new PrintWriter(conn.getOutputStream());

    // 發送請求參數

//     out.print(URLEncoder.encode(data,"UTF-8"));

    out.print(data);

    // 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);

    log.error("發送 POST 請求出現異常!"+e);

    e.printStackTrace();

    }

    //使用finally塊來關閉輸出流、輸入流

    finally{

    try{

    if(out!=null){

    out.close();

    }

    if(in!=null){

    in.close();

    }

    }

    catch(IOException ex){

    ex.printStackTrace();

    }

    }

    return result;

    } 

    

    /**

     * 向指定URL發送GET方法的請求

     * 

     * @param url

     *            發送請求的URL

     * @param param

     *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。

     * @return URL 所表明遠程資源的響應結果

     */

    public static String sendGet(String url, HashMap<String, String> data) {

        String result = "";

        BufferedReader in = null;

        try {

            String urlNameString = url + "?" + httpQuery(data);

            URL realUrl = new URL(urlNameString);

            // 打開和URL之間的鏈接

            URLConnection connection = realUrl.openConnection();

            // 設置通用的請求屬性

            connection.setConnectTimeout(5000);

            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            

            // 創建實際的鏈接

            connection.connect();

            // 獲取全部響應頭字段

//            Map<String, List<String>> map = connection.getHeaderFields();

//            // 遍歷全部的響應頭字段

//            for (String key : map.keySet()) {

//                System.out.println(key + "--->" + map.get(key));

//            }

            // 定義 BufferedReader輸入流來讀取URL的響應

            in = new BufferedReader(new InputStreamReader(

                    connection.getInputStream()));

            String line;

            while ((line = in.readLine()) != null) {

                result += line;

            }

        } catch (Exception e) {

            log.error("發送GET請求出現異常!",e);

        }

        // 使用finally塊來關閉輸入流

        finally {

            try {

                if (in != null) {

                    in.close();

                }

            } catch (Exception e2) {

                e2.printStackTrace();

            }

        }

        return result;

    }

/**

* http請求(get方式)

* @param url

* @param data

* @return

* @throws IOException 

*/

public static String testrequestUrl(String url, HashMap<String, String> data,int proid)

throws Exception {


// HttpURLConnection conn = null;

InputStreamReader streamReader = null;

BufferedReader bufferedReader;

StringBuilder sb = null;

String line;

try

{

// if GET....

// URL requestUrl = new URL(url + "?" + httpBuildQuery(data));

URL requestUrl = new URL(url);

HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();


conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");


conn.addRequestProperty("protocolid",String.valueOf(proid));

conn.setDoInput(true);

conn.setDoOutput(true);

conn.setRequestMethod("POST");

conn.connect();

PrintWriter writer = new PrintWriter(conn.getOutputStream());

// System.out.println(url+"?" +httpBuildQuery(data));

writer.print(httpBuildQuery(data));

writer.flush();

writer.close();


streamReader = new InputStreamReader(conn.getInputStream(), "UTF-8");

} catch (Exception e) {


// streamReader = new InputStreamReader(conn.getErrorStream(), "UTF-8");

log.error("testrequestUrl err", e);

} finally {

if (streamReader != null) {

bufferedReader = new BufferedReader(streamReader);

sb = new StringBuilder();

while ((line = bufferedReader.readLine()) != null) {

sb.append(line);

}

}

}

if (sb != null)

{

return sb.toString();

}

return null;

}

/**

* postHttp

* @param url

* @param data

* @return 字節流

* @throws Exception

*/

public static InputStream requestUrl2(String url, HashMap<String, String> data) throws Exception

{


try

{

// if GET....

// URL requestUrl = new URL(url + "?" + httpBuildQuery(data));

URL requestUrl = new URL(url);

HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();


conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");


conn.setDoInput(true);

conn.setDoOutput(true);

conn.connect();

PrintWriter writer = new PrintWriter(conn.getOutputStream());


// System.out.println(url+"?" +httpBuildQuery(data));

writer.print(httpBuildQuery(data));

writer.flush();

writer.close();


return conn.getInputStream();

} catch (Exception e)

{


log.error("requestUrl err", e);

} finally

{


}



return null;

}

/**

* 參數編碼

* @param data

* @return 

*/

public static String httpBuildQuery(HashMap<String, String> data) {

String ret = "";

String k, v;

Iterator<String> iterator = data.keySet().iterator();

while (iterator.hasNext()) {

k = iterator.next();

v = data.get(k);

try {

ret += URLEncoder.encode(k, "utf8") + "=" + URLEncoder.encode(v, "utf8");

} catch (UnsupportedEncodingException e) {

}

ret += "&";

}

return ret.substring(0, ret.length() - 1);

}

/**

* 短信參數編碼(短信內容GBK)

* @param data

* @return

*/

public static String httpQuery(HashMap<String, String> data) {

String ret = "";

String k, v;

Iterator<String> iterator = data.keySet().iterator();

while (iterator.hasNext()) {

k = iterator.next();

v = data.get(k);

try {

if (k.equals("msg"))

{

ret += k + "=" + URLEncoder.encode(v, "GBK");

// ret += k + "=" + Utils.changeCharset(k, "GBK");

}else{

ret += k + "=" + v;

}

} catch (UnsupportedEncodingException e) {

}

ret += "&";

}

System.out.println(ret);

log.info("requestinfo=>" + ret);

return ret.substring(0, ret.length() - 1);

/**

* 使用 HMAC-SHA1 簽名方法對對encryptText進行簽名(小米)

* @param encryptText 被簽名的字符串

* @param encryptKey 密鑰

* @return 返回被加密後的字符串

* @throws Exception

*/

public static String hmacSHA1Encrypt(HashMap<String, String> params, String encryptKey) 

{

String encryptText = sortString(params);

byte[] data;

try

{

data = encryptKey.getBytes(ENCODING);


// 根據給定的字節數組構造一個密鑰,第二參數指定一個密鑰算法的名稱

SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);


// 生成一個指定 Mac 算法 的 Mac 對象

Mac mac = Mac.getInstance(MAC_NAME);


// 用給定密鑰初始化 Mac 對象

mac.init(secretKey);

byte[] text = encryptText.getBytes(ENCODING);


// 完成 Mac 操做

byte[] digest = mac.doFinal(text);

StringBuilder sBuilder = bytesToHexString(digest);


return sBuilder.toString();

} catch (Exception e)

{

log.error("hmacSHA1Encrypt err:", e);

}

return null;

}


/**

* 轉換成Hex

* @param bytesArray

*/

public static StringBuilder bytesToHexString(byte[] bytesArray)

{

if (bytesArray == null)

{

return null;

}

StringBuilder sBuilder = new StringBuilder();

for (byte b : bytesArray)

{

String hv = String.format("%02x", b);

sBuilder.append(hv);

}

return sBuilder;

}


/**

* 將參數按照字母順序排序

* @param data

* @return

*/

public static String sortString(HashMap<String, String> data){

String[] signArray = {"appId","session","uid"};

StringBuilder sb = new StringBuilder();

for (String key : signArray)

{

String value = data.get(key);

if (value != null && !value.equals("")){

try

{

sb.append(URLEncoder.encode(key, ENCODING))

 .append("=")

 .append(URLEncoder.encode(value, ENCODING))

 .append("&");

catch (Exception e)

{


}

}

}

String result = sb.toString();

return result.substring(0, result.length() - 1);

}

/**

* get方式提交短信內容

* @param url

* @return

*/

private static String submit(String url) {

        String re = "";

        int byteMax = 50;

        try {

            URL myurl = new URL(url);

            URLConnection urlcon = myurl.openConnection();

            urlcon.setUseCaches(false);

            urlcon.connect();

            InputStream inputstream = urlcon.getInputStream();//輸出

            byte[] buff = new byte[byteMax];

            ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();

            int ins;

            while ((ins = inputstream.read(buff)) >= 0) {

                bytearrayoutputstream.write(buff, 0, ins);

            }

            re = new String(bytearrayoutputstream.toByteArray());

            re.trim();

        } catch (MalformedURLException ex) {

        log.error("submit SMS MalformedURLException:", ex);

        } catch (IOException ex) {

           log.error("submit SMS ioexception:", ex);

        }


        return re;

    }

    

}

相關文章
相關標籤/搜索