接着教程1写的 一些通用的接口函数,接收解析参数等我去掉了,你们自己加,给微信传输的参数看我上一个教程中链接有解释。
1、查询签约contract_id 函数,查看签约有没有效果,签约id是什么
private Map<String, Object> _queryContract(String openid){
Map<String, Object> signMap = new TreeMap<>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
// 升序排序
return obj1.compareTo(obj2);
}
}
);
signMap.put("appid",appid);
signMap.put("mch_id",mch_id);
signMap.put("openid",openid);
signMap.put("plan_id",plan_id);
signMap.put("version","1.0");
String sign=getSign(signMap);
StringBuilder XML = new StringBuilder();
XML.append("<xml>");
XML.append("<appid><![CDATA["+appid+"]]></appid>");
XML.append("<mch_id><![CDATA["+mch_id+"]]></mch_id>");
XML.append("<openid><![CDATA["+openid+"]]></openid>");
XML.append("<plan_id><![CDATA["+plan_id+"]]></plan_id>");
XML.append("<version><![CDATA[1.0]]></version>");
XML.append("<sign><![CDATA["+sign+"]]></sign>");
XML.append("</xml>");
String xml = XML.toString();
// 调用请求微信接口函数 并return结果
HttpsClientUtil httpsClientUtil = new HttpsClientUtil();
String wxResponseText = null;
try{
wxResponseText=httpsClientUtil.doPostXml(wxQueryContractUrl, xml);
}catch(Exception e){
results.put("success",false);
results.put("msg", "_queryContract_查询签约状态请求失败");
results.put("message", e);
return results;
}
Document document = null;
//开始解析xml字符串
try{
document = DocumentHelper.parseText(wxResponseText);
}catch(Exception e){
results.put("success",false);
results.put("msg", "_queryContract_查询签约状态请求失败");
results.put("message", e);
return results;
}
Element root = document.getRootElement();
Element successEl=root.element("return_code");//查询状态
String success=successEl.getStringValue();
if(success.equals("SUCCESS")){//此次查询成功
Element resultCodeEL = root.element("result_code"); //业务结果
String resultCode = resultCodeEL.getStringValue();
if( resultCode.equals("SUCCESS") ){//判断业务结果
//存放结果数据
Map<String,Object> item= new HashMap<>();
Element contractEl=root.element("contract_id");
String contract_id=contractEl.getStringValue();
results.put("contract_id",contract_id);
results.put("success", true);
}else if( resultCode.equals("FAIL") ){
Element errCodeEl=root.element("err_code");//错误代码
String errCode=errCodeEl.getStringValue();
Element errCodeDesEl=root.element("err_code_des");//错误代码描述
String errCodeDes=errCodeDesEl.getStringValue();
results.put("success",false);
results.put("msg",errCode);
results.put("message", errCodeDes);
}
}else if(success.equals("FAIL")){
Element msgEl=root.element("return_msg");//错误原因
String msg=msgEl.getStringValue();
results.put("success",false);
results.put("msg",msg);
results.put("message", msg);
}
return results;
}
2、查询订单状态
/查询微信订单接口selectPayOrder
public String selectPayOrder() throws Exception {
if(this.param==null || this.param.isEmpty()){
try {
this.param = getParamFromRequest();
}catch(Exception ex){
results.put("success", false);
results.put("msg", "参数错误");
results.put("message", ex.toString());
rootLogger.error("getUserStatus--------传入参数有误!");
rootLogger.error(ex);
return JSON;
}
if( this.param==null ){
results.put("success", false);
results.put("msg", "参数不足");
results.put("message", "缺失参数param");
rootLogger.error("getUserStatus------传入参数不足,获取不到用户信息!");
return JSON;
}
}
Object param_deserialize;
try {
param_deserialize = JSONUtil.deserialize(this.param);
}catch (Exception e){
results.put("success", false);
results.put("msg", "参数解析错误");
results.put("message", e.getMessage());
rootLogger.error("getUserStatus------参数解析错误!");
rootLogger.error(e);
return JSON;
}
Map<String, Object> queryMap = null;
try {
queryMap = (Map<String, Object>)param_deserialize;
} catch (ClassCastException ex1) {
results.put("success", false);
results.put("msg", "参数解析错误");
results.put("message", ex1.getMessage());
rootLogger.error("getUserStatus------用户信息参数解析错误!");
rootLogger.error(ex1);
return JSON;
}
if(queryMap.get("orderNo").equals("")||queryMap.get("orderNo")==null){
results.put("success", false);
results.put("msg", "传入订单号为空");
return JSON;
}
// **** 从传入对象中获取订单号
String orderNo=(String) queryMap.get("orderNo");
String nonce_str= MD5Utils.getNonceStr(32);//随机字符串
// **** 将所有参数组装成map排序
Map<String, Object> signMap = new TreeMap<String, Object>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
// 升序排序
return obj1.compareTo(obj2);
}
}
);
signMap.put("appid",appid);
signMap.put("mch_id",mch_id);
signMap.put("out_trade_no",orderNo);
signMap.put("nonce_str",nonce_str);
//调用组合签名字符串函数,获取签名结果
String sign=getSign(signMap);
// ****: 开始拼接xml
StringBuilder XML = new StringBuilder();
XML.append("<xml>");
XML.append("<appid><![CDATA["+appid+"]]></appid>");
XML.append("<mch_id><![CDATA["+mch_id+"]]></mch_id>");
XML.append("<out_trade_no><![CDATA["+orderNo+"]]></out_trade_no>");
XML.append("<nonce_str><![CDATA["+nonce_str+"]]></nonce_str>");
XML.append("<sign><![CDATA["+sign+"]]></sign>");
XML.append("</xml>");
String xml = XML.toString();
// ****: 调用请求微信接口函数 并return结果
HttpsClientUtil httpsClientUtil = new HttpsClientUtil();
// **** 开始调用请求微信接口
try {
//请求微信接口,储存结果
String wxResponseText = httpsClientUtil.doPostXml(wxQueryOrderUrl, xml);
//开始解析xml字符串
Document document = DocumentHelper.parseText(wxResponseText);
Element root = document.getRootElement();
Element successEl=root.element("return_code");
String success=successEl.getStringValue();
Element msgEl=root.element("return_msg");
String msg=msgEl.getStringValue();//getTextTrim
//开始判断结果
if(success.equals("SUCCESS")){//判断握手结果
Element resultCodeEl=root.element("result_code");
String resultCode=resultCodeEl.getStringValue();
if( resultCode.equals("SUCCESS") ){//判断业务结果
Element openidEl=root.element("openid");
String openid=openidEl.getStringValue();
Element trade_stateEl=root.element("trade_state");
String trade_state=trade_stateEl.getStringValue();
Element total_feeEl=root.element("total_fee");
String total_fee=total_feeEl.getStringValue();
Element transaction_idEl=root.element("transaction_id");
String transaction_id=transaction_idEl.getStringValue();
Map<String,Object> item= new HashMap<String,Object>();
item.put("orderNo",orderNo);
item.put("openid",openid);
item.put("trade_state",trade_state);
item.put("total_fee",total_fee);
item.put("transaction_id",transaction_id);
results.put("success",true);
results.put("data",item);
}else if( resultCode.equals("FAIL") ){
Element errCodeEl=root.element("err_code");//错误代码
String errCode=errCodeEl.getStringValue();
Element errCodeDesEl=root.element("err_code_des");//错误代码描述
String errCodeDes=errCodeDesEl.getStringValue();
results.put("success", false);
results.put("msg", errCodeDes);
results.put("message", errCode);
}
}else if(success.equals("FAIL")){
results.put("success", false);
results.put("msg", "请求微信接口出错");
results.put("message", msg);
}
}catch (Exception e){
results.put("success", false);
results.put("msg", "请求微信接口出错");
results.put("message", e.getMessage());
rootLogger.error("请求微信接口出错");
rootLogger.error(e);
}
return JSON;
}
3、申请退款
// 申请退款接口
public String refundOrder() throws Exception{
if(this.param==null || this.param.isEmpty()){
this.param=getParamFromRequest();
if( this.param==null ){
results.put("success", false);
results.put("msg", "参数不足");
results.put("message", "缺失参数param");
rootLogger.error("queryState-------缺失参数param");
return JSON;
}
}
Object param_deserialize;
try {
param_deserialize = JSONUtil.deserialize(param);
}catch (Exception e){
results.put("success", false);
results.put("msg", "参数解析错误");
results.put("message", e.getMessage());
rootLogger.error("queryState-------参数解析错误!");
rootLogger.error(e);
return JSON;
}
Map<String, String> paramMap;
try{
paramMap = (Map<String, String>)param_deserialize;
}catch(ClassCastException ex2){
results.put("success", false);
results.put("msg", "参数格式不正确");
results.put("message", ex2.getMessage());
rootLogger.error("queryState-------参数格式不正确!");
rootLogger.error(ex2);
return JSON;
}
//验证签名**验签方面伍勇做....
//开始获取参数并判断
int total_fee=Integer.parseInt( paramMap.get("amount") );//订单金额
int refund_fee=Integer.parseInt( paramMap.get("refund_fee") );//退款金额
String out_refund_no=paramMap.get("out_refund_no");//退款商户订单号-商户系统内部的退款单号唯一
String transaction_id=paramMap.get("transaction_id");//微信支付订单号
//生成随机字符串
String nonce_str= MD5Utils.getNonceStr(32);//随机字符串
//下面这些是存数据库用
String openid=paramMap.get("openid");
String time=paramMap.get("time");
String orderNo=paramMap.get("orderNo");
String lineName=paramMap.get("lineName");
String stationName=paramMap.get("stationName");
String start_station=paramMap.get("start_station");
String end_station=paramMap.get("end_station");
// TODO: 签名数据源
Map<String,Object> refundData=new TreeMap<String, Object>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
// 升序排序
return obj1.compareTo(obj2);
}
});
refundData.put("appid",appid);
refundData.put("mch_id",mch_id);
refundData.put("nonce_str",nonce_str);
refundData.put("transaction_id",transaction_id);
refundData.put("out_refund_no",out_refund_no);
refundData.put("total_fee",total_fee);
refundData.put("refund_fee",refund_fee);
//调用组合签名字符串函数,获取签名结果
String sign=getSign(refundData);
// TODO: 开始拼接xml
StringBuilder XML = new StringBuilder();
XML.append("<xml>");
XML.append("<appid><![CDATA["+appid+"]]></appid>");
XML.append("<mch_id><![CDATA["+mch_id+"]]></mch_id>");
XML.append("<nonce_str><![CDATA["+nonce_str+"]]></nonce_str>");
XML.append("<transaction_id><![CDATA["+transaction_id+"]]></transaction_id>");
XML.append("<out_refund_no><![CDATA["+out_refund_no+"]]></out_refund_no>");
XML.append("<total_fee><![CDATA["+total_fee+"]]></total_fee>");
XML.append("<refund_fee><![CDATA["+refund_fee+"]]></refund_fee>");
XML.append("<sign><![CDATA["+sign+"]]></sign>");
XML.append("</xml>");
String xml = XML.toString();
// TODO: 调用请求微信接口函数 并return结果
try{
HttpsClientUtil httpsClientUtil = new HttpsClientUtil();
String wxResponseText= httpsClientUtil.doPostXml(wxRefundUrl, xml);
//开始解析xml字符串
Document document = DocumentHelper.parseText(wxResponseText);
Element root = document.getRootElement();
Element returnCodeEL=root.element("return_code");//握手状态
String returnCode=returnCodeEL.getStringValue();
Element returnMsgEl;
String returnMsg;
if(returnCode.equals("SUCCESS")){//判断握手结果
//握手成功
Element resultCodeEl=root.element("result_code");
String resultCode=resultCodeEl.getStringValue();
if(resultCode.equals("SUCCESS")){//判断业务结果
//获取结果数据
Element refundIdEl=root.element("refund_id");
String refundId=refundIdEl.getStringValue();
//返回给前台
results.put("refundId",refundId);
results.put("success",true);
//申请成功 开始储存数据库表
Map<String,String> saveData= new HashMap<String,String>();
saveData.put("transactionId",transaction_id);
saveData.put("total_fee",(total_fee+"") );
saveData.put("refund_fee",(refund_fee+"") );
saveData.put("out_refund_no",out_refund_no );
saveData.put("refund_id",refundId );
saveData.put("openid",openid);//
saveData.put("time",time);
saveData.put("orderNo",orderNo);
saveData.put("lineName",lineName );
saveData.put("stationName",stationName);//
saveData.put("start_station",start_station);
saveData.put("end_station",end_station);
//开始调用sql
try{
dbExecutor.insert("com.sutpc.dao.PayDao.saveRefundOrder",saveData);
}catch (Exception e){
rootLogger.error("doWxPay-----存储失败!");
rootLogger.error(e);
}
}else if(resultCode.equals("FAIL")){
Element errCodeEl=root.element("err_code");//错误代码
String errCode=errCodeEl.getStringValue();
Element errCodeDesEl=root.element("err_code_des");//错误代码描述
String errCodeDes=errCodeDesEl.getStringValue();
results.put("success",false);
results.put("message",errCode);
results.put("msg", errCodeDes);
}
}else if(returnCode.equals("FAIL")){
//握手失败
returnMsgEl=root.element("return_msg");
returnMsg=returnMsgEl.getStringValue();
results.put("success",false);
results.put("msg","请求微信失败");
results.put("message",returnMsg);
}
}catch (Exception e){
results.put("success",false);
results.put("msg","请求微信失败");
results.put("message","微信拒接请求,未安装证书");
}
return JSON;
}
4、查询退款结果
// 查询退款结果 wxSelectRefund
public String selectRefund() throws Exception{
if(this.param==null || this.param.isEmpty()){
this.param=getParamFromRequest();
if( this.param==null ){
results.put("success", false);
results.put("msg", "参数不足");
results.put("message", "缺失参数param");
rootLogger.error("queryState-------缺失参数param");
return JSON;
}
}
Object param_deserialize;
try {
param_deserialize = JSONUtil.deserialize(param);
}catch (Exception e){
results.put("success", false);
results.put("msg", "参数解析错误");
results.put("message", e.getMessage());
rootLogger.error("queryState-------参数解析错误!");
rootLogger.error(e);
return JSON;
}
Map<String, String> paramMap;
try{
paramMap = (Map<String, String>)param_deserialize;
}catch(ClassCastException ex2){
results.put("success", false);
results.put("msg", "参数格式不正确");
results.put("message", ex2.getMessage());
rootLogger.error("selectRefund-------参数格式不正确!");
rootLogger.error(ex2);
return JSON;
}
String refund_id=paramMap.get("refund_id");
if(refund_id.equals("") || refund_id==null){
results.put("success", false);
results.put("msg", "参数不正确");
results.put("message", "refund_id is null");
rootLogger.error("selectRefund-------缺少refund_id参数!");
return JSON;
}
// TODO: 签名数据源
Map<String,Object> selectRefundData=new TreeMap<String, Object>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
// 升序排序
return obj1.compareTo(obj2);
}
});
selectRefundData.put("appid",appid);
selectRefundData.put("mch_id",mch_id);
selectRefundData.put("refund_id",refund_id);
//生成随机字符串
String nonce_str= MD5Utils.getNonceStr(32);//随机字符串
selectRefundData.put("nonce_str",nonce_str);
String sign=getSign(selectRefundData);
// TODO: 开始拼接xml
StringBuilder XML = new StringBuilder();
XML.append("<xml>");
XML.append("<appid><![CDATA["+appid+"]]></appid>");
XML.append("<mch_id><![CDATA["+mch_id+"]]></mch_id>");
XML.append("<nonce_str><![CDATA["+nonce_str+"]]></nonce_str>");
XML.append("<refund_id><![CDATA["+refund_id+"]]></refund_id>");
XML.append("<sign><![CDATA["+sign+"]]></sign>");
XML.append("</xml>");
String xml = XML.toString();
try{
HttpsClientUtil httpsClientUtil = new HttpsClientUtil();
String wxResponseText= httpsClientUtil.doPostXml(wxSelectRefund, xml);
//开始解析xml字符串
Document document = DocumentHelper.parseText(wxResponseText);
Element root = document.getRootElement();
Element returnCodeEL=root.element("return_code");//握手状态
String returnCode=returnCodeEL.getStringValue();
Element returnMsgEl;
String returnMsg;
if(returnCode.equals("SUCCESS")){//判断握手结果
//握手成功
Element resultCodeEl=root.element("result_code");
String resultCode=resultCodeEl.getStringValue();
if(resultCode.equals("SUCCESS")){//判断业务结果
//获取结果数据
Element refundStatusEl=root.element("refund_status_0");
String refundStatus=refundStatusEl.getStringValue();
Element refundRecvAccoutEl=root.element("refund_recv_accout_0");
String refundRecvAccout=refundRecvAccoutEl.getStringValue();
//返回给前台
results.put("refund_status",refundStatus);
results.put("refund_recv_accout",refundRecvAccout);
results.put("refund_id",refund_id);
results.put("success",true);
//申请成功 开始储存数据库表
Map<String,String> saveData= new HashMap<String,String>();
saveData.put("refund_status",refundStatus);//状态 SUCCESS—退款成功 FAIL—退款失败 PROCESSING—退款处理中 NOTSURE—未确定,需要商户原退款单号重新发起
saveData.put("refund_recv_accout",refundRecvAccout);//退到哪1)退回银行卡:2)退回支付用户零钱:
saveData.put("refund_id",refund_id);
//开始调用sql
try{
dbExecutor.insert("com.sutpc.dao.PayDao.updateRefundOrder",saveData);
}catch (Exception e){
rootLogger.error("doWxPay-----存储失败!");
rootLogger.error(e);
}
}else if(resultCode.equals("FAIL")){
Element errCodeEl=root.element("err_code");//错误代码
String errCode=errCodeEl.getStringValue();
Element errCodeDesEl=root.element("err_code_des");//错误代码描述
String errCodeDes=errCodeDesEl.getStringValue();
results.put("success",false);
results.put("message",errCode);
results.put("msg", errCodeDes);
//失败 记录失败原因 开始储存数据库表
Map<String,String> saveData= new HashMap<String,String>();
saveData.put("err_code",errCode);
saveData.put("err_code_des",errCodeDes);
saveData.put("refund_id",refund_id);
//开始调用sql
try{
dbExecutor.update("com.sutpc.dao.PayDao.updateRefundOrder",saveData);
}catch (Exception e){
rootLogger.error("doWxPay-----存储失败!");
rootLogger.error(e);
}
}
}else if(returnCode.equals("FAIL")){
//握手失败
returnMsgEl=root.element("return_msg");
returnMsg=returnMsgEl.getStringValue();
results.put("success",false);
results.put("msg","请求微信失败");
results.put("message",returnMsg);
}
}catch (Exception e){
results.put("success",false);
results.put("msg","请求微信失败");
results.put("message","连接微信请求失败");
}
return JSON;
}
5、查询订单状态2
// 查询订单状态接口
public String queryOrder() throws Exception {
if(this.param==null || this.param.isEmpty()){
this.param=getParamFromRequest();
if( this.param==null ){
results.put("success", false);
results.put("msg", "参数不足");
results.put("message", "缺失参数param");
rootLogger.error("queryOrder--------缺失参数param!");
return JSON;
}
}
Object param_deserialize;
try {
param_deserialize = JSONUtil.deserialize(param);
}catch (Exception e){
results.put("success", false);
results.put("msg", "参数解析错误");
results.put("message", e.getMessage());
rootLogger.error("queryOrder--------参数解析错误!");
rootLogger.error(e);
return JSON;
}
Map<String, String> paramMap;
try{
paramMap = (Map<String, String>)param_deserialize;
}catch(ClassCastException ex2){
results.put("success", false);
results.put("msg", "参数格式不正确");
results.put("message", ex2.getMessage());
rootLogger.error("queryOrder--------参数格式不正确!");
rootLogger.error(ex2);
return JSON;
}
//判断参数是否正确
String out_trade_no=paramMap.get("orderNo");
if( out_trade_no==null || out_trade_no.equals("") ){
results.put("success", false);
results.put("msg", "订单号错误");
results.put("message", "orderNo参数不存在或空");
rootLogger.error("queryOrder--------订单号错误:orderNo参数不存在或空!");
return JSON;
}
//将所有参数组装成map排序
Map<String, Object> signMap = new TreeMap<String, Object>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
// 升序排序
return obj1.compareTo(obj2);
}
}
);
signMap.put("mch_id",mch_id);
signMap.put("appid",appid);
signMap.put("out_trade_no",out_trade_no);
//生成随机字符串
String nonce_str= MD5Utils.getNonceStr(32);
signMap.put("nonce_str",nonce_str);
signMap.put("sign_type","MD5");
//获取签名结果
String sign=getSign(signMap);
//拼接XML
String xml = "<xml>" +
"<appid><![CDATA[" + appid + "]]></appid>" +
"<mch_id><![CDATA[" + mch_id + "]]></mch_id>" +
"<nonce_str><![CDATA[" + nonce_str + "]]></nonce_str>" +
"<out_trade_no><![CDATA[" + out_trade_no + "]]></out_trade_no>" +
"<sign><![CDATA[" + sign + "]]></sign>" +
"<sign_type><![CDATA[MD5]]></sign_type>" +
"</xml>";
// TODO: 调用请求微信接口函数 并return结果
HttpsClientUtil httpsClientUtil = new HttpsClientUtil();
String wxResponseText=httpsClientUtil.doPostXml(wxQueryOrderUrl, xml);
//开始解析xml字符串
Document document = DocumentHelper.parseText(wxResponseText);
Element root = document.getRootElement();
Element successEl=root.element("return_code");//查询状态
String success=successEl.getStringValue();
//开始判断结果
if(success.equals("SUCCESS")){//判断查询状态
Element resultCodeEL=root.element("result_code"); //业务结果
String resultCode=resultCodeEL.getStringValue();
if( resultCode.equals("SUCCESS") ){//判断业务结果
//存放结果数据
Map<String,Object> item= new HashMap<String,Object>();
Element outTradeNoEl=root.element("out_trade_no");//商户订单号 和 其实传入的订单号一样
String outTradeNo=outTradeNoEl.getStringValue();
//订单目前状态 : SUCCESS—支付成功 REFUND—转入退款 NOTPAY—未支付 CLOSED—已关闭 ACCEPT—已接收,等待扣款 PAY_FAIL--支付失败(其他原因,如银行返回失败)
Element tradeStateEl=root.element("trade_state");
String tradeState=tradeStateEl.getStringValue();
if( tradeState.equals("SUCCESS") ){ //判断支付结果是什么
item.put("status", 1);
}else{
item.put("status", -1);
}
item.put("orderId",outTradeNo);
results.put("result",item);
results.put("success",true);
}else if( resultCode.equals("FAIL") ){
Element errCodeEl=root.element("err_code");//错误代码
String errCode=errCodeEl.getStringValue();
Element errCodeDesEl=root.element("err_code_des");//错误代码描述
String errCodeDes=errCodeDesEl.getStringValue();
results.put("success",false);
results.put("msg",errCode);
results.put("message", errCodeDes);
rootLogger.warn("queryOrder--------查询结果错误!");
rootLogger.warn(errCodeDes);
}
}else if(success.equals("FAIL")){
Element msgEl=root.element("return_msg");//错误原因
String msg=msgEl.getStringValue();
results.put("success",false);
results.put("msg",msg);
rootLogger.error("queryOrder--------查询失败!");
rootLogger.error(msg);
}
return JSON;
}
HttpsClientUtil 实现代码, 不过我们这个架构比较老。。
package com.sutpc.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.omg.IOP.Encoding;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.net.URL;
import java.net.URLEncoder;
import java.security.Key;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/*
* 利用HttpClient进行post请求的工具类
*/
public class HttpsClientUtil {
public String doPost(String url, Map<String,String> map) throws Exception{
String result = null;
HttpClient httpClient = new SSLClient();
HttpPost httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator 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, "UTF-8");
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity, "UTF-8");
}
}
return result;
}
public String doGet(String url, Map<String,String> map) throws Exception{
String result = null;
HttpClient httpClient = new SSLClient();
String param="";
for(String nameKey:map.keySet()){
param += nameKey+"="+map.get(nameKey)+"&";
}
param = param.substring(0,param.length()-1);
String urlNameString = url + "?" + param;
HttpGet httpGet = new HttpGet(urlNameString);
HttpResponse response = httpClient.execute(httpGet);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity, "UTF-8");
}
}
return result;
}
public String doPostXml(String url, String xml) throws Exception{
String result = null;
HttpClient httpClient = new SSLClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type","text/xml;charset=UTF-8");
StringEntity stringEntity = new StringEntity(xml, "UTF-8");
stringEntity.setContentEncoding("UTF-8");
httpPost.setEntity(stringEntity);
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity, "UTF-8");
}
}
return result;
}
public String httpPostXmlStr(String url, String xml) throws Exception{
HttpClient httpClient = HttpClients.createDefault();
// HttpClient httpClient = new SSLClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8");
//设置参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("data", xml));
httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
String result = null;
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity, "UTF-8");
}
}
return result;
}
}
SSLClient 实现
package com.sutpc.utils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
//用于进行Https请求的HttpClient
public class SSLClient extends DefaultHttpClient{
public SSLClient() throws Exception{
super();
//传输协议需要根据自己的判断
SSLContext ctx = SSLContext.getInstance("TLSv1.2");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
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));
}
}