java HttpClient Post 請求和Get 請求

/**
 * HttpClient業務
 *
 * @author 
 * @version 1.0
 */
public class HttpClient implements java.io.Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private static final int OK = 200;  // OK: Success!
    private static final int ConnectionTimeout = 25000;
    private static final int ReadTimeout = 1200000;
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final String _GET = "GET";
    private static final String _POST = "POST";

    /**
     * Get 請求
     *
     * @param url 請求地址
     * @return 輸出流對象
     * @throws
     */
    public Response get(String url) throws IOException {
        return httpRequest(url, _GET, null);
    }

    /**
     * Post 請求
     *
     * @param url 請求地址
     * @param postData 提交數據
     * @return 輸出流對象
     * @throws
     */
    public Response post(String url,String postData) throws IOException {
        return httpRequest(url, _POST, postData);
    }

    /**

    /**
     * 獲取http請求連接
     *
     * @param url 連接地址
     * @return http連接對象
     * @throws IOException
     */
    private HttpURLConnection getHttpURLConnection(String url) throws IOException {
        URL urlGet = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlGet.openConnection();
        return con;
    }

    /**
     * 通過http協議請求url
     *
     * @param url 提交地址
     * @param method 提交方式
     * @param postData 提交數據
     * @return 響應流
     * @throws
     */
    private Response httpRequest(String url, String method, String postData) throws IOException {
        Response res = null;
        OutputStream output;
        HttpURLConnection http;

        //創建https請求連接
        http = getHttpURLConnection(url);
        //判斷https是否爲空,如果爲空返回null響應
        if (http != null) {
            //設置Header信息
            setHttpHeader(http, method);
            //判斷是否需要提交數據
            if (method.equals(_POST) && null != postData) {
                //講參數轉換爲字節提交
                byte[] bytes = postData.getBytes("UTF-8");
                //設置頭信息
                http.setRequestProperty("Content-Length", Integer.toString(bytes.length));
                //開始連接
                http.connect();
                //獲取返回信息
                output = http.getOutputStream();
                output.write(bytes);
                output.flush();
                output.close();
            } else {
                //開始連接
                http.connect();
            }
            //創建輸出對象
            res = new Response(http);
            //獲取響應代碼
            if (res.getStatus() == OK) {
                return res;
            }
        }

        return res;
    }

    private void setHttpHeader(HttpURLConnection httpUrlConnection, String method)
            throws IOException {
        //設置header信息
        httpUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        //設置User-Agent信息
        httpUrlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
        //設置可接受信息
        httpUrlConnection.setDoOutput(true);
        //設置可輸入信息
        httpUrlConnection.setDoInput(true);
        //設置請求方式
        httpUrlConnection.setRequestMethod(method);
        httpUrlConnection.setConnectTimeout(ConnectionTimeout);
        httpUrlConnection.setReadTimeout(ReadTimeout);
        //設置編碼
        httpUrlConnection.setRequestProperty("Charsert", "UTF-8");
    }

    public static String getUrl(Map<String, String> params, String charset)
            throws UnsupportedEncodingException {
        StringBuffer buffer = new StringBuffer("?");
        if (params == null && params.isEmpty()) {
            return null;
        }
        // 否則的話,開始拼接需要傳遞的值,也就是URL?AA==BB&CC==EE這樣的類似的連接值
        Set<Map.Entry<String, String>> entries = params.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String name = entry.getKey();
            String value = entry.getValue();
            // 還需要進行一次判斷是否爲空,一定要謹慎
            if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(value)) {
                // 如果不爲空的話,開始進行連接操作
                buffer.append(name).append("=").append(URLEncoder.encode(value, charset)).append("&");
            }

        }
        return buffer.toString().substring(0, buffer.toString().length() - 1);

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章