所有工具類(lèi)
在日常開(kāi)發(fā)中,我們經(jīng)常需要通過(guò)http協(xié)議去調(diào)用網(wǎng)絡(luò)內(nèi)容,雖然java自身提供了net相關(guān)工具包,但是其靈活性和功能總是不如人意,于是有人專(zhuān)門(mén)搞出一個(gè)httpclient類(lèi)庫(kù),來(lái)方便進(jìn)行Http操作。對(duì)于httpcore的源碼研究,我們可能并沒(méi)有達(dá)到這種層次,在日常開(kāi)發(fā)中也只是需要的時(shí)候,在網(wǎng)上百度一下,然后進(jìn)行調(diào)用就行。在項(xiàng)目中對(duì)于這個(gè)工具類(lèi)庫(kù)也許沒(méi)有進(jìn)行很好的封裝。在哪里使用就寫(xiě)在哪些,很多地方用到,就在多個(gè)地方寫(xiě)。反正是復(fù)制粘貼,很方便,但是這樣就會(huì)導(dǎo)致項(xiàng)目中代碼冗余。所以這里簡(jiǎn)單的對(duì)httpcient的簡(jiǎn)單操作封裝成一個(gè)工具類(lèi),統(tǒng)一放在項(xiàng)目的工具包中,在使用的時(shí)候直接從工具包中調(diào)用,不需要寫(xiě)冗余代碼。
HttpClientUtil
package zj.http.util; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.log4j.Logger; import zj.common.exception.ServiceException; import zj.http.bean.ICallBackMethod; /** * httpClient工具類(lèi) * * @version 1.00 (2014.09.15) * @author SHNKCS 張軍 {@link <a target=_blank href="http://m.sfpk123.com">張軍個(gè)人網(wǎng)站</a> <a target=_blank href="http://user.qzone.qq.com/360901061/">張軍QQ空間</a>} */ public class HttpClientUtil { private static transient final Logger logger = Logger.getLogger(HttpClientUtil.class); /** * get請(qǐng)求 * * @param url * 請(qǐng)求地址 * @return 響應(yīng)數(shù)據(jù) * @throws Exception */ public static String get(String url) { return get(url, null); } /** * get請(qǐng)求 * * @param url * 請(qǐng)求地址 * @param callBack * 設(shè)置參數(shù)s * @return 響應(yīng)數(shù)據(jù) * @throws Exception */ public static String get(String url, ICallBackMethod callBack) { String resultString = null; HttpClient httpClient = new HttpClient(); GetMethod method = new GetMethod(url); try { // method.setRequestHeader(new Header("", "")); if (callBack != null) { callBack.setMethod(method); } int resultCode = httpClient.executeMethod(method); if (resultCode == 200) { resultString = method.getResponseBodyAsString(); } logger.debug("調(diào)用方法返回結(jié)果[" + resultCode + "]:" + resultString); return resultString; } catch (Exception e) { throw new ServiceException(e); } finally { if (method != null) { try { method.releaseConnection(); } catch (Exception e2) { } } if (httpClient != null) { // 上面的httpPost.releaseConnection()只是把連接歸還client,沒(méi)有關(guān)閉 // 加上下面這一句,才真正把不用的連接關(guān)閉 // 如果不手動(dòng)關(guān)閉連接,每個(gè)連接都是保持180秒后才會(huì)自動(dòng)斷開(kāi),會(huì)占用大量的連接。 try { httpClient.getHttpConnectionManager().closeIdleConnections(0); } catch (Exception e) { logger.info(e.getMessage(), e); } } // try { // method.releaseConnection(); // ((SimpleHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown(); // } catch (Exception e) { // e.printStackTrace(); // } } } /** * XML.post請(qǐng)求 * * @param url * 請(qǐng)求地址 * @param content * 請(qǐng)求內(nèi)容 * @return 響應(yīng)數(shù)據(jù) * @throws Exception */ public static String postXML(String url, String content) { return post(url, content, "application/xml", "UTF-8"); } /** * JSON.post請(qǐng)求 * * @param url * 請(qǐng)求地址 * @param content * 請(qǐng)求內(nèi)容 * @return 響應(yīng)數(shù)據(jù) * @throws Exception */ public static String postJSON(String url, String content) { return post(url, content, "application/json", "UTF-8"); } /** * post請(qǐng)求 * * @param url * 請(qǐng)求地址 * @param content * 請(qǐng)求內(nèi)容 * @param contentType * 請(qǐng)求類(lèi)型 * @see contentType值說(shuō)明 * @see application/x-www-form-urlencoded:窗體數(shù)據(jù)被編碼為名稱(chēng)/值對(duì)。這是標(biāo)準(zhǔn)的編碼格式。這是默認(rèn)的方式 * @see multipart/form-data:窗體數(shù)據(jù)被編碼為一條消息,頁(yè)上的每個(gè)控件對(duì)應(yīng)消息中的一個(gè)部分。二進(jìn)制數(shù)據(jù)傳輸方式,主要用于上傳文件 * @see text/html * @see text/xml * @param charset * 請(qǐng)求編碼 * @return 響應(yīng)數(shù)據(jù) * @throws Exception */ public static String post(String url, String content, String contentType, String charset) { return post(url, content, contentType, charset, null); } /** * post請(qǐng)求 * * @param url * 請(qǐng)求地址 * @param content * 請(qǐng)求內(nèi)容 * @see application/x-www-form-urlencoded:窗體數(shù)據(jù)被編碼為名稱(chēng)/值對(duì)。這是標(biāo)準(zhǔn)的編碼格式。這是默認(rèn)的方式 * @see multipart/form-data:窗體數(shù)據(jù)被編碼為一條消息,頁(yè)上的每個(gè)控件對(duì)應(yīng)消息中的一個(gè)部分。二進(jìn)制數(shù)據(jù)傳輸方式,主要用于上傳文件 * @see text/html * @see text/xml * @param callBack * 設(shè)置參數(shù) * @return 響應(yīng)數(shù)據(jù) * @throws Exception */ public static String postJSON(String url, String content, ICallBackMethod callBack) { return post(url, content, "application/json", "UTF-8", callBack); } /** * post請(qǐng)求 * * @param url * 請(qǐng)求地址 * @param content * 請(qǐng)求內(nèi)容 * @param contentType * 請(qǐng)求類(lèi)型 * @see contentType值說(shuō)明 * @see application/x-www-form-urlencoded:窗體數(shù)據(jù)被編碼為名稱(chēng)/值對(duì)。這是標(biāo)準(zhǔn)的編碼格式。這是默認(rèn)的方式 * @see multipart/form-data:窗體數(shù)據(jù)被編碼為一條消息,頁(yè)上的每個(gè)控件對(duì)應(yīng)消息中的一個(gè)部分。二進(jìn)制數(shù)據(jù)傳輸方式,主要用于上傳文件 * @see text/html * @see text/xml * @param charset * 請(qǐng)求編碼 * @param callBack * 設(shè)置參數(shù) * @return 響應(yīng)數(shù)據(jù) * @throws Exception */ public static String post(String url, String content, String contentType, String charset, ICallBackMethod callBack) { String resultString = null; HttpClient httpClient = new HttpClient(); PostMethod method = new PostMethod(url); try { if (callBack == null) { // 默認(rèn)設(shè)置請(qǐng)求類(lèi)型 method.setRequestHeader(new Header("Content-Type", contentType)); } else { callBack.setMethod(method); } // method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ""); // 禁用重試 // DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false); // method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);// 重試次數(shù)0次 // httpClient.setParams(new HttpClientParams() { // private static final long serialVersionUID = 1458469810048748607L; // { // // setSoTimeout(uploadTimeOut); // // 連接超時(shí)時(shí)間 // setSoTimeout(120000); // } // }); // contentType值說(shuō)明 // application/x-www-form-urlencoded:窗體數(shù)據(jù)被編碼為名稱(chēng)/值對(duì)。這是標(biāo)準(zhǔn)的編碼格式。這是默認(rèn)的方式 // multipart/form-data:窗體數(shù)據(jù)被編碼為一條消息,頁(yè)上的每個(gè)控件對(duì)應(yīng)消息中的一個(gè)部分。二進(jìn)制數(shù)據(jù)傳輸方式,主要用于上傳文件 // text/plain:窗體數(shù)據(jù)以純文本形式進(jìn)行編碼,其中不含任何控件或格式字符。 method.setRequestEntity(new StringRequestEntity(content, contentType, charset)); int resultCode = httpClient.executeMethod(method); if (resultCode == 200) { resultString = method.getResponseBodyAsString(); } logger.debug("調(diào)用方法返回結(jié)果[" + resultCode + "]:" + resultString); return resultString; } catch (Exception e) { throw new ServiceException(e); } finally { if (method != null) { try { method.releaseConnection(); } catch (Exception e2) { } } if (httpClient != null) { // 上面的httpPost.releaseConnection()只是把連接歸還client,沒(méi)有關(guān)閉 // 加上下面這一句,才真正把不用的連接關(guān)閉 // 如果不手動(dòng)關(guān)閉連接,每個(gè)連接都是保持180秒后才會(huì)自動(dòng)斷開(kāi),會(huì)占用大量的連接。 try { httpClient.getHttpConnectionManager().closeIdleConnections(0); } catch (Exception e) { logger.info(e.getMessage(), e); } } // try { // ((SimpleHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown(); // } catch (Exception e) { // e.printStackTrace(); // } } } }
ICallBackMethod
package zj.http.bean; import org.apache.commons.httpclient.HttpMethodBase; /** * httpClient工具類(lèi)回調(diào) * * @version 1.00 (2014.09.15) * @author SHNKCS 張軍 {@link <a target=_blank href="http://m.sfpk123.com">張軍個(gè)人網(wǎng)站</a> <a target=_blank href="http://user.qzone.qq.com/360901061/">張軍QQ空間</a>} */ public interface ICallBackMethod { /** * 設(shè)置方法參數(shù) * * @param method */ public void setMethod(HttpMethodBase method); }
CallBackMethod
package zj.http.bean; import org.apache.commons.httpclient.HttpMethodBase; /** * httpClient工具類(lèi)回調(diào) * * @version 1.00 (2014.09.15) * @author SHNKCS 張軍 {@link <a target=_blank href="http://m.sfpk123.com">張軍個(gè)人網(wǎng)站</a> <a target=_blank href="http://user.qzone.qq.com/360901061/">張軍QQ空間</a>} */ public class CallBackMethod implements ICallBackMethod{ @Override public void setMethod(HttpMethodBase method) { } }
測(cè)試類(lèi)
@Test public void get測(cè)試() throws Exception { try { String newUrl = "http://www.baidu.com"; String r = HttpClientUtil.get(newUrl); System.out.println(r); } catch (Exception e) { e.printStackTrace(); } } @Test public void post測(cè)試() throws Exception { try { Map<String, Object> jsonMap = new HashMap<String, Object>(); jsonMap.put("name", "8779001"); jsonMap.put("password", "123"); String json = JSON.toJSONString(jsonMap); String r = HttpClientUtil.postJSON("https://agent.ybagent9.com/login", json); System.out.println(r); } catch (Exception e) { e.printStackTrace(); } }
本文為張軍原創(chuàng)文章,轉(zhuǎn)載無(wú)需和我聯(lián)系,但請(qǐng)注明來(lái)自張軍的軍軍小站,個(gè)人博客http://m.sfpk123.com
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
