直接上代碼把,伸手黨麻煩點下贊,謝謝。 java
/** * 通用封裝發送HTTP請求 * @author dan * create 2014-3-24上午10:18:55 */ public class HttpSender<T> { private static Log log = LogFactory.getLog(HttpSender.class); /** * 發送實體 * @param obj 發送類的實體 * @param url 發送的url * @return */ public String sendPost(T obj, String url) { try { BeanInfo bif = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertis = bif.getPropertyDescriptors(); HttpClient httpclient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); List<NameValuePair> params = new ArrayList<NameValuePair>(); for (PropertyDescriptor pd : propertis) { Object o = pd.getReadMethod().invoke(obj, null); String str = null; if(o!=null){ str = o.toString(); } params.add(new BasicNameValuePair(pd.getName(), str)); } UrlEncodedFormEntity uefEntity; uefEntity = new UrlEncodedFormEntity(params, "UTF-8"); post.setEntity(uefEntity); // 設置請求表單 HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); if (entity == null) { return ""; } return EntityUtils.toString(entity); } catch (Exception e) { e.printStackTrace(); log.error("自省出錯!"+e); } return ""; } public String sendGet(T obj, String url) { try { BeanInfo bif = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertis = bif.getPropertyDescriptors(); HttpClient httpclient = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpParams httpParams = new BasicHttpParams(); for (PropertyDescriptor pd : propertis) { Object o = pd.getReadMethod().invoke(obj, null); String str = null; if(o!=null){ str = o.toString(); } httpParams.setParameter(pd.getName(), str); } get.setParams(httpParams); // 設置請求表單 HttpResponse response = httpclient.execute(get); HttpEntity entity = response.getEntity(); if (entity == null) { return ""; } return EntityUtils.toString(entity); } catch (Exception e) { e.printStackTrace(); log.error("自省出錯!"+e); } return ""; } }
如下是測試代碼 post
@Test public void testGet(){ String str = "http://192.168.1.4:8088/Charge/Charges"; HttpSender<TransferBean> sender = new HttpSender<TransferBean>(); TransferBean transferBean = new TransferBean(); transferBean.setAccountID("123"); String result = sender.sendGet(transferBean,str); System.out.print(result); }測試過程當中,仍是必需要帶參數的不然會報空指針,致使內省失敗,有空再改。