直接上代码把,伸手党麻烦点下赞,谢谢。
/**
* 通用封装发送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 "";
}
}
以下是测试代码
@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);
}