有时候我们需要进行远程调用,跨域,有很多可选方案,例如 jsonp ,RMI, HttpClient.
我感觉 HttpClient属于一次写好,以后只要直接用就可以了,很方便,节约时间。
/* * 利用HttpClient进行post请求的工具类 */public class HttpClientUtil { public static String doPost(String url,Mapmap,String charset){ HttpClient httpClient = null; HttpPost httpPost = null; String result = null; try{ httpClient = new SSLClient(); httpPost = new HttpPost(url); //设置参数 List list = new ArrayList (); Iterator > iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Entry elem = (Entry ) iterator.next(); list.add(new BasicNameValuePair(elem.getKey(),elem.getValue())); } if(list.size() > 0){ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset); httpPost.setEntity(entity); } HttpResponse response = httpClient.execute(httpPost); if(response != null){ HttpEntity resEntity = response.getEntity(); if(resEntity != null){ result = EntityUtils.toString(resEntity,charset); } } }catch(Exception ex){ ex.printStackTrace(); } return result; }}
public class SSLClient extends DefaultHttpClient{ public SSLClient() throws Exception{ super(); SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[]{tm}, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = this.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); }}
调用:
/** *方法用途:使用 *@param args *2017年1月11日 */ public static void main(String[] args) { String url=""; Mapparam=new HashMap (); String charset="utf-8"; String result=doPost(url,param,charset); System.out.println(result); }
param 的 key 为参数名称, value 为参数的值。对方可以用过 request.getParameter("");得到值。