微信支付H5支付&退款【二】

代碼來了...........................

前端部分代碼:

<div class="con">
		<div class="order-title">
			<h3 class="title">賬單列表</h3>
			<ul>
				<li>訂單編號:<span ng-bind="record.cases_num"></span></li>
				<li>日期:<span ng-bind="record.create_time"></span></li>
			</ul>
		</div>
		<div class="list">
			<div id="billList"></div>
		</div>
		<div class="mess">
			<div class="type">
				<div class="tit">訂單總金額:</div>
				<div class="text" ng-bind="record.total_money"></div>
			</div>
			<div class="type">
				<div class="tit">已支付金額:</div>
				<div class="text" ng-bind="record.pay_money"></div>
			</div>
		</div>
		<div class="mess">
			<div class="type">
				<div class="tit">支付金額:</div>
				<div class="text">
					<input name="pay_money" type="text" ng-model="record.money" readOnly="true" />
				</div>
			</div>
			<div class="checkbox">
				<input name="pay" type="radio" value="2" checked />
				<span>微信</span>
			</div>
			
		</div>
		<div class="mess">
			<div class="type">
				<div class="tit">退款金額:</div>
				<div class="text">
					<input name="refund_money" type="text" ng-model="record.refund_money" min="0" max="record.refund_money" />
				</div>
			</div>
			<div class="tips">(請輸入小於已支付金額的數額)</div>
		</div>
	</div>
	<div class="action-buttons">
		<button type="button" class="btn btn-success" ng-click="moneyChongzhi(record.money)">確定支付</button>
		<button type="button" class="btn btn-success" ng-click="moneyRefund(record.refund_money)">退款</button>
	</div>
 //提交支付申請   金額 ,訂單編號  --付款-付的錢數爲後臺返回數據
		$scope.moneyChongzhi=function(num){
			var kind = $("input[name='pay']:checked").val();
			if(kind==null || kind ==""){
				alert("請選擇支付方式....");
				return;
			}
	   		var toUrl = "";
			if("1" == kind){
				// 支付寶
				toUrl = settings.serverUrl+'/alipay/index?WIDtotal_fee='+num+'&cases_num='+$scope.record.cases_num+"&enterprise_id="+$scope.record.company_id+"&source_id="+$scope.record.source_id;
			} else  if("2"== kind) {
				// 微信  wxPayH5
				toUrl = settings.serverUrl+'/alipay/wxPayH5?cases_num='+$scope.record.cases_num+'&WIDtotal_fee='+num+"&enterprise_id="+$scope.record.company_id+"&source_id="+$scope.record.source_id;
			}
			window.location.assign(toUrl);
	   	}
		
		//提交退款申請
		$scope.moneyRefund = function(refund_money){
			if(parseInt(refund_money)>parseInt($scope.record.pay_money)){
				alert("請輸入小於訂單已支付的金額...");
				return;
			}
			if(refund_money <=0){
				alert("請輸入金額大於0....");
				return;
			}
			toUrl = settings.serverUrl+'/refund/refundWx?cases_num='+$scope.record.cases_num+'&refund_fee='+refund_money+"&enterprise_id="+$scope.record.company_id+"&source_id="+$scope.record.source_id;
			window.location.assign(toUrl);
		}

配置參數:

#微信支付相關信息  appid | 商業號 | key
#微信公衆號身份的唯一標識。審覈通過後,在微信發送的郵件中查看
weixin.body = XXX服務商平臺
weixin.appid = w..........6..8
#受理商ID,身份標識
weixin.mch_id = 111111111
#商戶支付密鑰Key。審覈通過後,在微信發送的郵件中查看
weixin.api_key = sdweqertvytxdedzsddw9999
#JSAPI接口中獲取openid,審覈後在公衆平臺開啓開發模式後可查看
weixin.appsecret = ....................................
#請求支付地址
weixin.ufdoder_url= https://api.mch.weixin.qq.com/pay/unifiedorder
#支付回調函數
weixin.notify_url_h5 = http://localhostUrl/adminapi/alipay/payNotify
#請求退款地址
weixin.refund_url = https://api.mch.weixin.qq.com/secapi/pay/refund
#查詢地址
weixin.orderquery_url = https://api.mch.weixin.qq.com/pay/orderquery
package com.apps.busi.web;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.apps.busi.service.AppAliPayService;
import com.apps.busi.service.CasesSerService;
import com.apps.common.config.Config;
import com.apps.common.database.DBTable;
import com.apps.common.util.HttpUtil;
import com.apps.common.util.PayCommonUtil;
import com.apps.common.util.XMLUtil;

import lombok.extern.slf4j.Slf4j;
 
/**
 * @author superY
 * @descrition 手機網站支付接口接入頁controller 2019年5月28日 上午10:40:12
 */
@Slf4j
@Controller
@RequestMapping("/alipay")
public class AppAliPayController extends BaseController {
	//private static final String Map = null;
	// 充值標識
	private Boolean czflg;
	@Autowired
	private AppAliPayService appAliPayService;
	
	@Autowired
	private  CasesSerService casesSerService;
	/**
	 * 微信H5支付
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 */
	@RequestMapping(value="/wxPayH5",produces = "text/html; charset=UTF-8")
	@ResponseBody
	public void wxPayH5(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
		String urlString = "";
		try {
			// 付款金額
			String total_fee = request.getParameter("WIDtotal_fee");
			//案件編號
			String cases_num  = request.getParameter("cases_num");
			// ip地址獲取
			String basePath = request.getServerName() + ":" + request.getServerPort();
			// 價格 注意:價格的單位是分
			String order_price = new BigDecimal(total_fee).multiply(new BigDecimal(100)).toString().split("\\.")[0];
			// 自己網站上的訂單號 (案件編號-10位隨機數)
			String out_trade_no =cases_num+"-"+PayCommonUtil.buildRandom(10);
			String spbill_create_ip = HttpUtil.getRealIp(request).split(",")[0];// 獲取發起電腦 ip
			String notify_url =Config.getValue("weixin.notify_url_h5").replaceAll("localhostUrl", basePath);
			//場景信息
			String scene_info = "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"https://www.baidu.com\",\"wap_name\": \"服務平臺\"}}";
			//下單
			Map map = appAliPayService.wxPayH5(out_trade_no,order_price,spbill_create_ip,notify_url,scene_info);
			//確認支付過後跳的地址,需要經過urlencode處理
			urlString ="http://enterprise.ipaosos.com/adminapi/alipay/queryH5?out_trade_no="+out_trade_no+"&cases_num="+cases_num;
			String mweb_url = map.get("mweb_url")+"&redirect_url="+URLEncoder.encode(urlString, "GBK");
			response.sendRedirect(mweb_url);
		} catch (Exception e) {
			log.debug(e+"");
		}
	}
	
	@RequestMapping(value="queryH5",method = RequestMethod.GET)
	@ResponseBody
	public void queryH5(HttpServletRequest request, HttpServletResponse response,RedirectAttributes attr,String out_trade_no,String cases_num) throws JDOMException, IOException {
		//查詢訂單
		Map mapQuery = appAliPayService.queryOrder(out_trade_no);
		String msg = "";
		if("SUCCESS".equalsIgnoreCase(mapQuery.get("trade_state").toString())) {
            //支付成功
			log.info("查詢 支付成功");
			msg = "pay_success";
		}else if("NOTPAY".equalsIgnoreCase(mapQuery.get("trade_state").toString())){
            //未支付
			log.info("查詢  未支付...");
			msg = "no_pay";
		}else {
            //支付失敗
			log.info("支付失敗.....");
			msg = "pay_faile";
		}
		String urlString = "http://enterprise.ipaosos.com/customer/#/payDetail/"+cases_num+"?msg="+msg;
		response.sendRedirect(urlString);
	}
	/**
	 * 執行回調 確認支付後處理事件 例如添加金額到數據庫等操作
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/payNotify",produces = "text/html; charset=UTF-8")
	@ResponseBody
	public void weixin_notify(HttpServletRequest request, HttpServletResponse response, ModelMap model)throws Exception {
		String xmlMsg = readData(request);
		Map params = XMLUtil.doXMLParse(xmlMsg);
		try {
			// 過濾空 設置 TreeMap
			SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
			Iterator it = params.keySet().iterator();
			while (it.hasNext()) {
				String parameter = (String) it.next();
				String parameterValue = params.get(parameter)+"";
				String v = "";
				if (null != parameterValue) {
					v = parameterValue.trim();
				}
				packageParams.put(parameter, v);
			}
			log.info(packageParams.toString());// 查看回調參數
			String resXml = "";
			// 處理業務開始
			if ("SUCCESS".equals((String) packageParams.get("result_code"))) {// 這裏是支付成功
				czflg = true;
				//執行自己的業務邏輯-start
				model.put("sHtmlText", "充值成功");
				try {
					synchronized (czflg) {
						//存儲數據
						appAliPayService.save(packageParams);
						czflg = false;
					}
				} catch (Exception e) {
					log.debug(e+"");
				}
				//執行自己的業務邏輯-end
				// 通知微信.異步確認成功.必寫.不然會一直通知後臺.八次之後就認爲交易失敗了.
				resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
			} else {
				model.put("sHtmlText", "充值失敗");
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[充值失敗]]></return_msg>" + "</xml> ";
			}
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			out.write(resXml.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			log.debug(e+"");
		}
 
	}
}

退款

package com.apps.busi.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.apps.busi.service.RefundService;
import com.apps.common.database.DBTable;
import com.apps.common.util.PayCommonUtil;
import lombok.extern.slf4j.Slf4j;
 
/**
 * @author superY
 * @descrition 手機網站退款接口接入頁controller 2019年5月29日 上午09:40:12
 */
@Slf4j
@Controller
@RequestMapping("/refund")
public class RefundController extends BaseController {
	@Autowired
	private RefundService refundService;
	
	/**
	 * 退款
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 */
	@Autowired
	@RequestMapping(value="/refundWx",produces = "text/html; charset=UTF-8")
	public void refundWx(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String result = "1";
			//訂單編號
			String cases_num = request.getParameter("cases_num");
			//退款金額 微信中金額單位是分
			String refund_fee =new BigDecimal(request.getParameter("refund_fee")).multiply(new BigDecimal(100)).toString().split("\\.")[0];
			//退款結果
			Map refund_result = new HashMap();
			//微信退款字段
			String out_refund_no = cases_num+"-"+PayCommonUtil.buildRandom(10);		
			//2.1.1退金額(原路退回)
			if("1".equals(type)) {//支付寶支付	(1:支付寶  2:微信 3:現金)
			} else if("2".equals(type)){//微信支付
			    log.info("退款金額  "+connectionRecordList.size());
				refund_result = refundService.refundWX(out_refund_no,connectionRecord.get("transaction_id").toString(),money,money);
				result = refundService.refundResult(refund_result);//退款結果進行操作
			}
		//重定向頁面
		String urlStr="http://www.bai.com/customer/#/detail/"+cases_num+"?msg="+result;
			response.sendRedirect(urlString);
		} catch (Exception e) {
			System.out.println(e+"");
			log.debug(e+"");
		}
	}
}

package com.apps.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.ConnectionPoolTimeoutException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import com.apps.busi.service.AppAliPayService;
import com.apps.common.config.Config;

import lombok.extern.slf4j.Slf4j;
/**
 * httputil
 * 
 * @author lvchaohua
 *
 */
@Slf4j
public class HttpUtil {

	//private static final Logger logger = LogManager.getLogger(HttpUtil.class);
	private static final String CHARSET = "UTF-8";
	private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
	private final static int SOCKET_TIMEOUT = 1000;
    //請求器的配置
    private static RequestConfig requestConfig;
    //HTTP請求器
    private static CloseableHttpClient httpClient;
	//public static String certLocalPath = "/WEB-INF/cert/apiclient_cert.p12"; 
 
    /**
     * 加載證書
     * @param path
     * @throws IOException
     * @throws KeyStoreException
     * @throws UnrecoverableKeyException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    private static void initCert( InputStream instream) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
        //拼接證書的路徑
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try {
            keyStore.load(instream, Config.getValue("weixin.mch_id").toCharArray());  //加載證書密碼,默認爲商戶ID
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } finally {
            instream.close();
        }
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, Config.getValue("weixin.mch_id").toCharArray())       //加載證書密碼,默認爲商戶ID
                .build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
 
        httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        //根據默認超時限制初始化requestConfig
        requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build();
 
    }

	 /**
     * 通過Https往API post xml數據
     * @param url   API地址
     * @param xmlObj   要提交的XML數據對象
     * @param path    當前目錄,用於加載證書
     * @return
     * @throws IOException
     * @throws KeyStoreException
     * @throws UnrecoverableKeyException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static String httpsRequest(String refund_url, String requestXML, InputStream stream) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
        //加載證書
        initCert(stream);
        String utf= "UTF-8";
        String result = null;
        HttpPost httpPost = new HttpPost(refund_url);
        //得指明使用UTF-8編碼,否則到API服務器XML的中文不能被成功識別
        StringEntity postEntity = new StringEntity(requestXML, utf);
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(postEntity);
        //設置請求器的配置
        httpPost.setConfig(requestConfig);
        try {
    		 HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, utf);
        } catch (ConnectionPoolTimeoutException e) {
           log.info("http get throw ConnectionPoolTimeoutException(wait time out)");
 
        } catch (ConnectTimeoutException e) {
        	 log.info("http get throw ConnectTimeoutException");
 
        } catch (SocketTimeoutException e) {
        	 log.info("http get throw SocketTimeoutException");
        } catch (Exception e) {
        	 log.info("http get throw Exception");
        } finally {
            httpPost.abort();
        }
 
        return result;
    }
	
	public static String postData(String urlStr, String data) {
		return postData(urlStr, data, null);
	}
 
	public static String postData(String urlStr, String data, String contentType) {
		BufferedReader reader = null;
		try {
			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setConnectTimeout(CONNECT_TIMEOUT);
			conn.setReadTimeout(CONNECT_TIMEOUT);
			if (contentType != null)
				conn.setRequestProperty("content-type", contentType);
			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), CHARSET);
			if (data == null)
				data = "";
			writer.write(data);
			writer.flush();
			writer.close();
 
			reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), CHARSET));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
				sb.append("\r\n");
			}
			return sb.toString();
		} catch (IOException e) {
		} finally {
			try {
				if (reader != null)
					reader.close();
			} catch (IOException e) {
			}
		}
		return null;
	}
	/**
	 * 獲取真實ip地址 通過阿帕奇代理的也能獲取到真實ip
	 * @param request
	 * @return
	 */
	public static String getRealIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * http get請求
	 * 
	 * @param url
	 *            請求地址
	 * @param params
	 *            請求參數
	 * @return
	 */
	public static String get(String url) {
		String result = "";
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpResponse response = httpClient.execute(httpGet);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					result = EntityUtils.toString(entity, CHARSET);
					return result;
				}
			} finally {
				response.close();
				httpClient.close();
			}
		} catch (Exception e) {
			//logger.error(e);
			//throw new RuntimeException(e);
			result=""+e;
			
		}
		return result;
	}

	/**
	 * http get請求
	 * 
	 * @param url
	 *            請求地址
	 * @param params
	 *            請求參數
	 * @return
	 */
	public static String get(String url, Map<String, Object> params) {
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			url = url + "?";
			for (Iterator<String> iterator = params.keySet().iterator(); iterator.hasNext();) {
				String key = iterator.next();
				String temp = key + "=" + params.get(key) + "&";
				url = url + temp;
			}
			url = url.substring(0, url.length() - 1);
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpResponse response = httpClient.execute(httpGet);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String str = EntityUtils.toString(entity, CHARSET);
					return str;
				}
			} finally {
				response.close();
				httpClient.close();
			}
		} catch (Exception e) {
			//logger.error(e);
			throw new RuntimeException(e);
		}
		return null;
	}

	/**
	 * http post請求
	 * 
	 * @param url
	 *            請求地址
	 * @param params
	 *            請求參數
	 * @return
	 */
	public static String post(String url, Map<String, Object> params) {
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			for (Iterator<String> iterator = params.keySet().iterator(); iterator.hasNext();) {
				String key = iterator.next();
				parameters.add(new BasicNameValuePair(key, params.get(key).toString()));
			}
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(parameters, CHARSET);
			httpPost.setEntity(uefEntity);
			CloseableHttpResponse response = httpClient.execute(httpPost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String str = EntityUtils.toString(entity, CHARSET);
					return str;
				}
			} finally {
				response.close();
				httpClient.close();
			}
		} catch (Exception e) {
		//	logger.error(e);
			throw new RuntimeException(e);
		}
		return null;
	}

	/**
	 * http post請求
	 * 
	 * @param url
	 *            請求地址
	 * @param params
	 *            請求參數
	 * @return
	 */
	public static String post(String url, String params) {
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			StringEntity sEntity = new StringEntity(params, CHARSET);
			httpPost.setEntity(sEntity);
			CloseableHttpResponse response = httpClient.execute(httpPost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, CHARSET);
				}
			} finally {
				response.close();
				httpClient.close();
			}
		} catch (Exception e) {
		//	logger.error(e);
			throw new RuntimeException(e);
		}
		return null;
	}
	public static String readUrl(String url) throws IOException{
		URL tric=new URL(url);
		StringBuffer  sb=new StringBuffer();
		BufferedReader in=new BufferedReader(new InputStreamReader(tric.openStream(),"UTF-8"));
		String inputLine;
		while((inputLine=in.readLine())!=null)
		{
			sb.append(inputLine);
			//System.out.println(inputLine);
		}
		in.close();
		return sb.toString();
	}
	
	/**
     * 向指定URL發送GET方法的請求
     * @param  url 發送請求的URL  "https://api.weixin.qq.com/send?access_token=rwsgsadg353";
     * @return URL 所代表遠程資源的響應結果
     */
	public static String sendGetUrl(String url) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url;
			URL realUrl = new URL(urlNameString);
			// 打開和URL之間的連接
			URLConnection connection = realUrl.openConnection();
			// 設置通用的請求屬性
			connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立實際的連接
			connection.connect();
			// 獲取所有響應頭字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍歷所有的響應頭字段
			for (String key : map.keySet()) {
				//System.out.println(key + "--->" + map.get(key));
			}
			// 定義 BufferedReader輸入流來讀取URL的響應
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			result=e.getMessage();
			System.out.println("發送GET請求出現異常!" + e);
			e.printStackTrace();
		}
		// 使用finally塊來關閉輸入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}
	

}
package com.juzhencms.apps.common.util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
 
/**
 * xml工具類
 * 
 * @author superY
 *
 */
public class XMLUtil {
 
	/**
	 * 解析xml,返回第一級元素鍵值對。如果第一級元素有子節點,則此節點的值是子節點的xml數據。
	 * 
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map doXMLParse(String strxml) throws JDOMException, IOException {
		strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
 
		if (null == strxml || "".equals(strxml)) {
			return null;
		}
 
		Map m = new HashMap();
 
		InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if (children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = XMLUtil.getChildrenText(children);
			}
 
			m.put(k, v);
		}
 
		// 關閉流
		in.close();
 
		return m;
	}
 
	/**
	 * 獲取子結點的xml
	 * 
	 * @param children
	 * @return String
	 */
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if (!list.isEmpty()) {
					sb.append(XMLUtil.getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}
		return sb.toString();
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章