1. 程式人生 > >HTTP請求工具類:HttpUtil.java

HTTP請求工具類:HttpUtil.java

HTTP請求工具類:

package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;

public class HttpUtil {

	final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	/**
	 * Post 請求超時時間和讀取資料的超時時間均為2000ms。
	 *
	 * @param urlPath
	 *            post請求地址
	 * @param parameterData
	 *            post請求引數
	 * @return String json字串,成功:code=1001,否者為其他值
	 * @throws Exception
	 *             連結超時異常、引數url錯誤格式異常
	 */
	public static String doPost(String urlPath, String parameterData,
			String who, String ip) throws Exception {

		if (null == urlPath || null == parameterData) { // 避免null引起的空指標異常
			return "";
		}
		URL localURL = new URL(urlPath);
		URLConnection connection = localURL.openConnection();
		HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

		httpURLConnection.setDoOutput(true);
		if (!StringUtils.isEmpty(who)) {
			httpURLConnection.setRequestProperty("who", who);
		}
		if (!StringUtils.isEmpty(ip)) {
			httpURLConnection.setRequestProperty("clientIP", ip);
		}
		httpURLConnection.setRequestMethod("POST");
		httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
		httpURLConnection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		httpURLConnection.setRequestProperty("Content-Length",
				String.valueOf(parameterData.length()));
		httpURLConnection.setConnectTimeout(18000);
		httpURLConnection.setReadTimeout(18000);

		OutputStream outputStream = null;
		OutputStreamWriter outputStreamWriter = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		StringBuilder resultBuffer = new StringBuilder();
		String tempLine = null;

		try {
			outputStream = httpURLConnection.getOutputStream();
			outputStreamWriter = new OutputStreamWriter(outputStream);

			outputStreamWriter.write(parameterData.toString());
			outputStreamWriter.flush();

			if (httpURLConnection.getResponseCode() >= 300) {
				throw new Exception(
						"HTTP Request is not success, Response code is "
								+ httpURLConnection.getResponseCode());
			}

			inputStream = httpURLConnection.getInputStream(); // 真正的傳送請求到服務端
			inputStreamReader = new InputStreamReader(inputStream);
			reader = new BufferedReader(inputStreamReader);

			while ((tempLine = reader.readLine()) != null) {
				resultBuffer.append(tempLine);
			}

		} finally {

			if (outputStreamWriter != null) {
				outputStreamWriter.close();
			}

			if (outputStream != null) {
				outputStream.close();
			}

			if (reader != null) {
				reader.close();
			}

			if (inputStreamReader != null) {
				inputStreamReader.close();
			}

			if (inputStream != null) {
				inputStream.close();
			}
		}
		return resultBuffer.toString();
	}
	
	
	/**
	 * Post 請求超時時間和讀取資料的超時時間均為2000ms。
	 *
	 * @param urlPath
	 *            post請求地址
	 * @param parameterData
	 *            post請求引數
	 * @return String json字串,成功:code=1001,否者為其他值
	 * @throws Exception
	 *             連結超市異常、引數url錯誤格式異常
	 */
	public static String doPostByJSON(String urlPath, JSONObject parameterData) throws Exception {
		
		if (null == urlPath || null == parameterData) { // 避免null引起的空指標異常
			return "";
		}
		URL localURL = new URL(urlPath);
		URLConnection connection = localURL.openConnection();
		HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
		
		httpURLConnection.setDoOutput(true);
		
		Set<String> keySet = parameterData.keySet();
		
		 Iterator it = keySet.iterator();
	      while(it.hasNext()){
	    	  String key = it.next().toString();
	    	  if("url".equals(key)){
	    		  continue;
	    	  }
	    	  String value = parameterData.get(key).toString();
	    	  connection.setRequestProperty(key, value);
	     }
		
		httpURLConnection.setRequestMethod("POST");
		httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
		httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		httpURLConnection.setRequestProperty("Content-Length",String.valueOf(parameterData.toJSONString().length()));
		httpURLConnection.setConnectTimeout(18000);
		httpURLConnection.setReadTimeout(18000);
		
		OutputStream outputStream = null;
		OutputStreamWriter outputStreamWriter = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		StringBuilder resultBuffer = new StringBuilder();
		String tempLine = null;
		
		try {
			outputStream = httpURLConnection.getOutputStream();
			outputStreamWriter = new OutputStreamWriter(outputStream);
			
			outputStreamWriter.write(parameterData.toString());
			outputStreamWriter.flush();
			
			if (httpURLConnection.getResponseCode() >= 300) {
				throw new Exception(
						"HTTP Request is not success, Response code is "
								+ httpURLConnection.getResponseCode());
			}
			
			inputStream = httpURLConnection.getInputStream(); // 真正的傳送請求到服務端
			inputStreamReader = new InputStreamReader(inputStream);
			reader = new BufferedReader(inputStreamReader);
			
			while ((tempLine = reader.readLine()) != null) {
				resultBuffer.append(tempLine);
			}
			
		} finally {
			
			if (outputStreamWriter != null) {
				outputStreamWriter.close();
			}
			
			if (outputStream != null) {
				outputStream.close();
			}
			
			if (reader != null) {
				reader.close();
			}
			
			if (inputStreamReader != null) {
				inputStreamReader.close();
			}
			
			if (inputStream != null) {
				inputStream.close();
			}
		}
		return resultBuffer.toString();
	}

	public static String doPost(String url, Map<String, Object> params)
			throws Exception {
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, Object> entry : params.entrySet()) {
			sb.append(entry.getKey()).append("=").append(entry.getValue())
					.append("&");
		}

		// no matter for the last '&' character

		return doPost(url, sb.toString(), "", "");
	}

	/**
	 * 向指定URL傳送GET方法的請求
	 *
	 * @param url
	 *            傳送請求的URL
	 * @param param
	 *            請求引數,請求引數應該是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表遠端資源的響應結果
	 */
	public static String sendGet(String url, String param, String who, String ip) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url;
			if (!"".equals(param)) {
				urlNameString = urlNameString + "?" + param;
			}
			URL realUrl = new URL(urlNameString);
			// 開啟和URL之間的連線
			URLConnection connection = realUrl.openConnection();
			// 設定通用的請求屬性
			if (!StringUtils.isEmpty(who)) {
				connection.setRequestProperty("who", who);
			}
			if (!StringUtils.isEmpty(ip)) {
				connection.setRequestProperty("clientIP", ip);
			}
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立實際的連線
			connection.connect();
			//bufReader = new BufferedReader(new InputStreamReader(in, "utf-8"));
			// 定義 BufferedReader輸入流來讀取URL的響應
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			logger.warn("傳送GET請求出現異常!", e);
		}
		// 使用finally塊來關閉輸入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				logger.warn("fail to close inputStream.", e2);
			}
		}
		return result;
	}

	public static String sendGet(String url, Map<String, Object> params)
			throws Exception {
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, Object> entry : params.entrySet()) {
			sb.append(entry.getKey()).append("=").append(entry.getValue())
					.append("&");
		}

		// no matter for the last '&' character

		return sendGet(url, sb.toString(), "", "");
	}
	
	
	public static String sendGet(String url, JSONObject parameterData) throws Exception {
		StringBuffer sb = new StringBuffer();
		
		Set<String> keySet = parameterData.keySet();
		
		 Iterator it = keySet.iterator();
	      while(it.hasNext()){
	    	  String key = it.next().toString();
	    	  if("param".equals(key)){
	    		  String value = parameterData.get(key).toString();
	    		  sb.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")).append("&");
	    	  }else{
	    		  String value = parameterData.get(key).toString();
	    		  sb.append(key).append("=").append(value).append("&");
	    	  }
	     }

		// no matter for the last '&' character
	      System.out.println(sb.toString());
		return sendGet(url, sb.toString(), "", "");
	}
	
	/**
     * 向指定 URL 傳送POST方法的請求
     * 
     * @param url
     *            傳送請求的 URL
     * @param param
     *            請求引數,請求引數應該是 name1=value1&name2=value2 的形式。
     * @return 所代表遠端資源的響應結果
     */
    public static String sendPost(String url, Map<String,Object> param) throws Exception {
//        PrintWriter out = null;
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("X-HW-ID", "videoAnalysisAPI");
            conn.setRequestProperty("X-HW-APPKEY", "J5ejD2Hh9in+ex7oMS+f0Q==");
            // 傳送POST請求必須設定如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
//            out = new PrintWriter(conn.getOutputStream());
//            out = new OutputStreamWriter(conn.getOutputStream(), "ISO-8859-1"); // 8859_1
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // 8859_1
            out.write(JSONObject.toJSONString(param));
//            out.write("{\"a\":\"b\"}");
            out.flush();
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
        	throw e;
        }
        finally{
            try{
                if(out!=null) out.close();
                if(in!=null)in.close();
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    
    
 
    public static String sendPost(String url, String param) throws Exception {
//        PrintWriter out = null;
    	System.out.println(1111111111);
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new 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)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 傳送POST請求必須設定如下兩行
         // 傳送POST請求必須設定如下兩行
            // 傳送POST請求必須設定如下兩行
    			conn.setDoOutput(true);
    			conn.setDoInput(true);
    			// 獲取URLConnection物件對應的輸出流
    			// out = new PrintWriter(conn.getOutputStream());
    			out = new OutputStreamWriter(conn.getOutputStream(), "utf-8"); // 8859_1
    			out.write(param); // post的關鍵所在
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
        	throw e;
        }
        finally{
            try{
                if(out!=null) out.close();
                if(in!=null)in.close();
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

}