使用 CloseableHttpClient

/** 

  * post json格式 

  * @param url 调用接口 

  * @param para  json格式数据 

  */ 

   public  static String sendPost(String url, String data) {  

          String response = null; 

          try { 

              CloseableHttpClient httpclient = null; 

              CloseableHttpResponse httpresponse = null; 

              try { 

                  httpclient = HttpClients.createDefault(); 

                  HttpPost httppost = new HttpPost(url); 

                  StringEntity stringentity = new StringEntity(data, 

                          ContentType.create("text/json", "UTF-8")); 

                  httppost.setEntity(stringentity); 

                  httpresponse = httpclient.execute(httppost);//关键一步 

                  response = EntityUtils 

                          .toString(httpresponse.getEntity(),"utf-8");//加上utf-8参数防止中文乱码 

                 System.out.println(response); 

              } finally { 

                  if (httpclient != null) { 

                      httpclient.close(); 

                  } 

                  if (httpresponse != null) { 

                      httpresponse.close(); 

                  } 

              } 

          } catch (Exception e) { 

              e.printStackTrace(); 

          } 

          return response; 

      }

使用HttpURLConnection

public class RequestUtil {
 private static Properties prop=getProp();
 public static String url="http://b2blib.198fc.cn:8081/b2blib/lotteryxml.php";
 /**
  * 向指定URL发送GET方法的请求
  * 
  * @param url
  *            发送请求的URL
  * @param param
  *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  * @return URL 所代表远程资源的响应结果
  */
 public static String sendGet(String url, String param) {
 String result = "";
 BufferedReader in = null;
 try {
 String urlNameString = url + "?" + param;
 URL realUrl = new URL(urlNameString);
 // 打开和URL之间的连接
 URLConnection connection = realUrl.openConnection();
 // 设置通用的请求属性
 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(),"utf-8"));
 String line;
 while ((line = in.readLine()) != null) {
 result += line;
 }
 } catch (Exception e) {
 System.out.println("发送GET请求出现异常!" + e);
 e.printStackTrace();
 }
 // 使用finally块来关闭输入流
 finally {
 try {
 if (in != null) {
 in.close();
 }
 } catch (Exception e2) {
 e2.printStackTrace();
 }
 }
 return result;
 }



/** 
  * @Description:使用URLConnection发送post 
  * @author:liuyc 
  * @time:2016年5月17日 下午3:26:52 
  */  
 public static String sendPost(String urlParam, PageData pd) {  
 StringBuffer resultBuffer = null;   
 // 构建请求参数  
 String json = ExchangeUtil.mapToXml(pd);
 HttpURLConnection conn = null;  
 OutputStreamWriter out = null;
 BufferedReader reader = null;
 try {
 URL realUrl = new URL(urlParam);  
 resultBuffer=new StringBuffer();
 // 打开和URL之间的连接  
 conn = (HttpURLConnection) realUrl.openConnection();  
 conn.setRequestMethod("POST");
 conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
 conn.setRequestProperty("connection", "keep-alive");
 conn.setUseCaches(false);//设置不要缓存
 conn.setInstanceFollowRedirects(true);
 conn.setDoOutput(true);
 conn.setDoInput(true);
 conn.connect();
 //POST请求
 out = new OutputStreamWriter(
 conn.getOutputStream());
 out.write(json);
 out.flush();
 //读取响应
 reader = new BufferedReader(new InputStreamReader(
 conn.getInputStream()));
 String lines;
 while ((lines = reader.readLine()) != null) {
 lines = new String(lines.getBytes(), "utf-8");
 resultBuffer.append(lines);
 }
 reader.close();
 // 断开连接
 conn.disconnect();


 } catch (Exception e) {
 System.out.println("发送 POST 请求出现异常!"+e);
 e.printStackTrace();
 }
 //使用finally块来关闭输出流、输入流
 finally{
 try{
 if(out!=null){
 out.close();
 }
 if(reader!=null){
 reader.close();
 }
 }
 catch(IOException ex){
 ex.printStackTrace();
 }
 }


 return resultBuffer.toString();
 }  
 /** 
  * @Description:使用URLConnection发送post 
  * @author:liuyc 
  * @time:2016年5月17日 下午3:26:52 
  */  
 public static String sendPut(String urlParam, PageData pd) {  
 StringBuffer resultBuffer = null;   
 // 构建请求参数  
 String json = JSONUtils.toJSONString(pd);
 HttpURLConnection conn = null;  
 OutputStreamWriter out = null;
 BufferedReader reader = null;
 try {  
 URL realUrl = new URL(urlParam);  
 resultBuffer=new StringBuffer();
 // 打开和URL之间的连接  
 conn = (HttpURLConnection) realUrl.openConnection();  
 conn.setRequestMethod("PUT");
 conn.setRequestProperty("Content-Type", "application/json");
 conn.setRequestProperty("connection", "keep-alive");
 conn.setUseCaches(false);//设置不要缓存
 conn.setInstanceFollowRedirects(true);
 conn.setDoOutput(true);
 conn.setDoInput(true);
 conn.connect();
 //POST请求
 out = new OutputStreamWriter(
 conn.getOutputStream());
 out.write(json);
 out.flush();
 //读取响应
 reader = new BufferedReader(new InputStreamReader(
 conn.getInputStream()));
 String lines;
 while ((lines = reader.readLine()) != null) {
 lines = new String(lines.getBytes(), "utf-8");
 resultBuffer.append(lines);
 }
 reader.close();
 // 断开连接
 conn.disconnect();


 } catch (Exception e) {
 System.out.println("发送 PUT 请求出现异常!"+e);
 e.printStackTrace();
 }
 //使用finally块来关闭输出流、输入流
 finally{
 try{
 if(out!=null){
 out.close();
 }
 if(reader!=null){
 reader.close();
 }
 }
 catch(IOException ex){
 ex.printStackTrace();
 }
 }


 return resultBuffer.toString();
 }  


 public static Properties getProp(){
 InputStream instream=RequestUtil.class.getClassLoader().getResourceAsStream("AppPay.properties");
 Properties prop = new Properties();
 try {
 prop.load(instream);
 instream.close();
 } catch (IOException e) {
 e.printStackTrace();
 }
 return prop;
 } 
 /******
  * 请求第三方接口
  * @param pd
  * @return
  * @throws Exception
  */
 public static String[] requestLottery(PageData pd)throws Exception{
 PageData temp = new PageData();
 String[] str=null;
 String result="";
 /*String userName=prop.getProperty("userName");
 String agenterId=prop.getProperty("agenterId");
 String orderId=pd.get("ORDER_TOTAL_ID").toString();*/
 // String sn=pd.getString("SN").toString();
 /*String issue=pd.get("TERM").toString();*/
 List<PageData> list = (List<PageData>)pd.get("PROGRAM");
 int lotteryType = Integer.parseInt(pd.get("LOTTERY_TYPE").toString());
 int transactionType=13005;
 if(lotteryType==2){
 transactionType=13010;
 }
 if(list!=null&&list.size()>0){
 str=new String[list.size()];


 for (int i=0 ;i<list.size();i++) {
 pd.put("PRICE", list.get(i).get("PRICE"));
 pd.put("TICKET_NUM", list.get(i).get("TICKET_NUM"));
 pd.put("BETS", list.get(i).get("BETS"));
 pd.put("MULTIPLE", list.get(i).get("MULTIPLE"));
 pd.put("METHOD_CODE", list.get(i).get("METHOD_CODE"));
 pd.put("SELECT_TYPE", list.get(i).get("SELECT_TYPE"));
 pd.put("PROGRAM_ID", list.get(i).get("PROGRAM_ID"));
 if(list.get(i).containsKey("UNIQUE_ID")){
 pd.put("UNIQUE_ID", list.get(i).get("UNIQUE_ID"));
 }
 PageData body = putBody(pd);
 temp.put("header", putHeader(pd,body,transactionType));
 temp.put("body", body);
 result = sendPost("http://b2blib.198fc.cn:8081/b2blib/lotteryxml.php", temp);
 str[i]=result;
 }
 }
 /*PageData resData = new PageData();
 resData.put("issue", pd.get("TERM"));
 resData.put("lotoId", pd.get("ORDER_TYPE1"));
 resData.put("orderId", orderId);
 resData.put("tickets", res);
 temp.put("body", resData);*/
 return str;
 }
 public static PageData putBody(PageData pd){
 String methodCode="0";
 String childType="0";
 if(pd.containsKey("METHOD_CODE")){
 methodCode = pd.get("METHOD_CODE").toString();
 }
 if(pd.containsKey("CHILD_TYPE")){
 childType=pd.get("CHILD_TYPE").toString();
 methodCode=childType;
 }


 LinkedHashMap<String,Object> element = new LinkedHashMap<String,Object>();
 PageData elements = new PageData();
 PageData body=new PageData();
 if(pd.containsKey("USER")){
 PageData user = (PageData) pd.get("USER");
 element.put("ticketuser", user.get("USER_NAME"));
 element.put("identify", user.get("ID_NUMBER"));
 element.put("phone", user.get("PHONE"));
 element.put("email",user.get("MAIL"));
 }
 if(pd.containsKey("PROGRAM_ID")){
 element.put("id", pd.get("PROGRAM_ID"));
 }
 if(pd.containsKey("SPECIES_CODE")){
 element.put("lotteryid", pd.get("SPECIES_CODE"));
 }
 if(pd.containsKey("TERM")){
 element.put("issue", pd.get("TERM"));
 }
 if(pd.containsKey("METHOD_CODE")||pd.containsKey("CHILD_TYPE")){
 element.put("childtype", methodCode);
 }
 if(pd.containsKey("SELECT_TYPE")){
 element.put("saletype",pd.get("SELECT_TYPE")); //玩法code 取自 方案中的玩法code
 }
 if(pd.containsKey("TICKET_NUM")){
 element.put("lotterycode",pd.get("TICKET_NUM")); //玩法code 取自 方案中的玩法code
 }
 if(pd.containsKey("MULTIPLE")){
 element.put("appnumbers", Integer.parseInt(pd.get("MULTIPLE").toString()));
 }
 if(pd.containsKey("BETS")){
 element.put("lotterynumber", Integer.parseInt(pd.get("BETS").toString()));
 }


 if(pd.containsKey("PRICE")){
 int price=(int)Double.parseDouble(pd.get("PRICE").toString());
 element.put("lotteryvalue",price*100); //玩法code 取自 方案中的玩法code
 }
 if(pd.containsKey("UNIQUE_ID")){
 element.put("id",pd.get("UNIQUE_ID"));
 }
 if(pd.containsKey("isbonus")){
 element.put("isbonus", pd.get("isbonus"));
 }
 if(pd.containsKey("BETLOTTERY_MODE")){
 String mode=pd.get("BETLOTTERY_MODE").toString();
 if(!StringUtils.isEmpty(mode)){
 element.put("betlotterymode", mode);
 }
 }
 elements.put("element", element);
 body.put("elements", elements);
 return body;
 }
 public static PageData putHeader(PageData pd,PageData elements,int transactionType) throws Exception{
 String userName=prop.getProperty("userName");
 String agenterId=prop.getProperty("agenterId");
 String proxyPwd=prop.getProperty("proxyPwd");
 PageData temp = new PageData();
 PageData body = new PageData();
 String sn="";
 if(pd.containsKey("SN")){
 sn=pd.getString("SN").toString();
 }else{
 sn=UuidUtil.getTimeStamp();
 }
 body.put("body",  elements);
 String str=AppUtil.getTimeStamp().trim()+proxyPwd.trim()+ExchangeUtil.requestMd5(body).trim();
 str=str.replaceAll("\\s", "").replaceAll("\n", "");
 String digest=MD5.md5(str);
 temp.put("messengerid", sn);
 temp.put("timestamp", AppUtil.getTimeStamp());
 temp.put("transactiontype", transactionType);
 temp.put("digest", digest);
 temp.put("agenterid", agenterId);
 temp.put("username", userName);
 return temp;
 }
 /********
  * 解析请求彩票接口返回的数据
  * @param string
  * @return
  * @throws Exception
  */
 public static PageData parseMap(String str)throws Exception{
 Map<String, Object> map = UnExchangeUtil.parseXmlStr(str);
 PageData temp = new PageData();
 if(map.containsKey("body")){
 Map body = (HashMap)map.get("body");
 if(body.containsKey("oelement")){
 Map oelement =(HashMap)body.get("oelement");
 if(oelement.get("errorcode").toString().equals("0")){
 temp.put("code", EnumsInfo.SUCCESS.getCode());
 if(body.containsKey("elements")){
 Map elements = (HashMap)body.get("elements");
 temp.put("data", elements.get("element"));
 }
 }else{
 temp.put("code", oelement.get("errorcode"));
 temp.put("data", oelement.get("errormsg"));
 }
 }
 }else{
 temp.put("code", EnumsInfo.FAIL.getCode());
 temp.put("desc", EnumsInfo.FAIL.getDesc());
 }
 return temp;
 }


 public static void main(String[] args) {
 PageData pd = new PageData();
 PageData temp = new PageData();
 PageData data = new PageData();
 data.put("SPECIES_CODE", "112");
 try {
 pd.put("SN", AppUtil.getTimeStamp()+IdworkerUtils.getRandomId());
 PageData header = putHeader(pd,putBody(data),1);
 temp.put("header", header);
 temp.put("body",putBody(data));
 String str = sendPost(url, temp);
 // System.out.println(ExchangeUtil.format(str));
 // System.out.println(orderSumbit(pd));
 Map<String, Object> map = UnExchangeUtil.parseXmlStr(str);
 Map result = (HashMap)map.get("body");
 Map resData=(HashMap)result.get("oelement");
 if(resData.containsKey("errorcode")&&resData.get("errorcode").toString().equals("0")){
 System.out.println("执行成功");
 }
 } catch (Exception e) {
 e.printStackTrace();
 }
 }


}