URL的openConnection()方法將返回一個URLConnection對象,該對象表示應用程序和 URL 之間的通信鏈接。程序可以通過URLConnection實例向該URL發送請求、讀取URL引用的資源。
驗證身份證號碼與姓名是否一致的接口:
http://132.228.156.103:9188/DataSync/CheckResult?SeqNo=1&ChannelID=1003&ID=41272xxxxx&Name=xxx
需求:
在用戶填入身份證號時校驗其准確性。
頁面:
var id_number = $("#idNumber").val(); var user_name = $("#staffName").val(); $.ajax({ type:'POST', url:contextPath + "/check/checkIdNumber.do", data:{ id_number:id_number, user_name:user_name }, dataType:'json', success:function(json){ if(json.result != "00"){ $.messager.alert('警告','姓名與身份證號碼不一致,請核對!'); }else{ $.ajax({ type : 'POST', url : contextPath + "/Staff/modifyIdNumber.do", data : { ID_NUMBER:id_number, mobileNumber:$("#mobileNumber").val() }, dataType : 'json', success : function(json) { if (json.status) { msgShow('系統提示', '實名認證成功', 'info'); isSimplePwd = true; $('#idNumberWindow').window('close'); }else{ msgShow('系統提示', json.info, 'warning'); } } }); } } });
控制層:
/** * 驗證身份證號碼與姓名是否一致 * @param request * @param response * @throws IOException */ @RequestMapping("/checkIdNumber.do") @ResponseBody public void checkIdNumber(HttpServletRequest request, HttpServletResponse response) throws IOException{ String id_number = request.getParameter("id_number"); String user_name = request.getParameter("user_name"); Map<String, String> param = new HashMap<String, String>(); param.put("ID", id_number); param.put("Name", user_name); param.put("SeqNo", "1");//流水號 param.put("ChannelID", "1003");//渠道號 String result = HttpUtil.sendPost(Constants.DATA_SYNC, param, "utf-8"); JSONObject resObj = JSONObject.fromObject(result); Map<String, Object> rs = new HashMap<String, Object>(); rs.put("result", resObj.get("result").toString()); rs.put("smsg", resObj.get("smsg").toString()); write(response, rs); }
數據返回頁面的另一種方式:(尤其是當返回結果是List集合時,不能使用write(response,rs))
BaseServletTool.sendParam(response, rs.toString());
服務層:
/** * POST請求,Map形式數據 * @param url 請求地址 * @param param 請求數據 * @param charset 編碼方式 */ public static String sendPost(String url, Map<String, String> param, String charset) { StringBuffer buffer = new StringBuffer(); if (param != null && !param.isEmpty()) { for (Map.Entry<String, String> entry : param.entrySet()) { buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue())).append("&"); } } buffer.deleteCharAt(buffer.length() - 1); PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection conn = realUrl.openConnection(); // 設置通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); //設置鑒權屬性 //connection.setRequestProperty("X-Authorization", " Bearer " + String.valueOf(param.get("token"))); // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(conn.getOutputStream()); // 發送請求參數 out.print(buffer); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送 POST 請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * TODO GET請求,字符串形式數據 * @param url 請求地址 * @param charset 編碼方式 * */ public String sendGet(String url, Map<String, String> param, String charset) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打開和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.setRequestProperty("X-Authorization", " Bearer " + String.valueOf(param.get("token"))); // 建立實際的連接 connection.connect(); // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset)); 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; }
根據不同的請求方式選擇sendPost()或sendGet()方法,如果需要鑒權,添加:
connection.setRequestProperty("X-Authorization", " Bearer " + String.valueOf(param.get("token")));
附HttpUtil.java
package com.system.tool; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; /** * 向指定服務器(外網)發送GET或POST請求工具類 * @author wangxiangyu * */ public class HttpUtil { private static int connectTimeOut = 5000; private static int readTimeOut = 10000; private static String requestEncoding = "UTF-8"; /** * GET請求,字符串形式數據 * @param url 請求地址 * @param charset 編碼方式 * */ public static String sendGet(String url, String charset) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打開和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.setRequestProperty("X-Authorization", " Bearer " + String.valueOf(param.get("token"))); // 建立實際的連接 connection.connect(); // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset)); 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; } /** * POST請求,字符串形式數據 * @param url 請求地址 * @param param 請求數據 * @param charset 編碼方式 * */ public static String sendPostUrl(String url, String param, String charset) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection conn = realUrl.openConnection(); // 設置通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(conn.getOutputStream()); // 發送請求參數 out.print(param); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送 POST 請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * POST請求,Map形式數據 * @param url 請求地址 * @param param 請求數據 * @param charset 編碼方式 */ public static String sendPost(String url, Map<String, String> param, String charset) { StringBuffer buffer = new StringBuffer(); if (param != null && !param.isEmpty()) { for (Map.Entry<String, String> entry : param.entrySet()) { buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue())).append("&"); } } buffer.deleteCharAt(buffer.length() - 1); PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection conn = realUrl.openConnection(); // 設置通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(conn.getOutputStream()); // 發送請求參數 out.print(buffer); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送 POST 請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * POST請求,字符串形式數據 * @param url 請求地址 * @param param 請求數據 */ public static String sendPost(String url, Map<String,Object> param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection conn = realUrl.openConnection(); // 設置通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("Content-Type", "application/form-data"); conn.setRequestProperty("Content-Length", String.valueOf(JsonUtil.simpleMapToJsonStr(param).length())); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(conn.getOutputStream()); // 發送請求參數 out.print(JsonUtil.simpleMapToJsonStr(param)); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); String line; while ((line = in.readLine()) != null) { result += line; } System.out.println("url>>>>>>>>:"+url); System.out.println("param>>>>>>>>:"+JsonUtil.simpleMapToJsonStr(param)); System.out.println("result>>>>>>>>:"+result); } catch (Exception e) { System.out.println("發送 POST 請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } public static String doPost(String reqUrl, Map<String, String> parameters, String recvEncoding) { HttpURLConnection url_con = null; String responseContent = null; String vchartset = recvEncoding == "" ? HttpUtil.requestEncoding : recvEncoding; try { StringBuffer params = new StringBuffer(); for (Iterator<?> iter = parameters.entrySet().iterator(); iter.hasNext();) { Entry<?, ?> element = (Entry<?, ?>) iter.next(); params.append(element.getKey().toString()); params.append("="); params.append(URLEncoder.encode(element.getValue().toString(), vchartset)); params.append("&"); } if (params.length() > 0) { params = params.deleteCharAt(params.length() - 1); } URL url = new URL(reqUrl); url_con = (HttpURLConnection) url.openConnection(); url_con.setRequestMethod("POST"); url_con.setConnectTimeout(HttpUtil.connectTimeOut); url_con.setReadTimeout(HttpUtil.readTimeOut); url_con.setDoOutput(true); byte[] b = params.toString().getBytes(); url_con.getOutputStream().write(b, 0, b.length); url_con.getOutputStream().flush(); url_con.getOutputStream().close(); InputStream in = url_con.getInputStream(); byte[] echo = new byte[10 * 1024]; int len = in.read(echo); responseContent = (new String(echo, 0, len)).trim(); int code = url_con.getResponseCode(); if (code != 200) { responseContent = "ERROR" + code; } } catch (IOException e) { System.out.println("網絡故障:" + e.toString()); } finally { if (url_con != null) { url_con.disconnect(); } } return responseContent; } public static String http(String url, Map<String, Object> params) { URL u = null; HttpURLConnection con = null; // 構建請求參數 StringBuffer sb = new StringBuffer(); if (params != null) { for (Entry<String, Object> e : params.entrySet()) { sb.append(e.getKey()); sb.append("="); sb.append(e.getValue()); sb.append("&"); } sb.substring(0, sb.length() - 1); } System.out.println("send_url:" + url); System.out.println("send_data:" + sb.toString()); // 嘗試發送請求 try { u = new URL(url); con = (HttpURLConnection) u.openConnection(); //// POST 只能為大寫,嚴格限制,post會不識別 con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); osw.write(JsonUtil.simpleMapToJsonStr(params)); osw.flush(); osw.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.disconnect(); } } // 讀取返回內容 StringBuffer buffer = new StringBuffer(); try { //一定要有返回值,否則無法把請求發送給server端。 BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String temp; while ((temp = br.readLine()) != null) { buffer.append(temp); buffer.append("\n"); } } catch (Exception e) { e.printStackTrace(); } return buffer.toString(); } }