有時候咱們須要進行遠程調用,跨域,有不少可選方案,例如 jsonp ,RMI, HttpClient.java
我感受 HttpClient屬於一次寫好,之後只要直接用就能夠了,很方便,節約時間。json
/* * 利用HttpClient進行post請求的工具類 */ public class HttpClientUtil { public static String doPost(String url,Map<String,String> map,String charset){ HttpClient httpClient = null; HttpPost httpPost = null; String result = null; try{ httpClient = new SSLClient(); httpPost = new HttpPost(url); //設置參數 List<NameValuePair> list = new ArrayList<NameValuePair>(); Iterator<Entry<String, String>> iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Entry<String,String> elem = (Entry<String, String>) 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=""; Map<String,String> param=new HashMap<String,String>(); String charset="utf-8"; String result=doPost(url,param,charset); System.out.println(result); }
param 的 key 爲參數名稱, value 爲參數的值。對方能夠用過 request.getParameter("");獲得值。工具