基於http協議的介面測試(1)
阿新 • • 發佈:2019-02-04
/** * 使用 HttpClient 需要以下 5 個步驟: 1. 建立 HttpClient 的例項 2. 建立某種連線方法的例項,在這裡是 httppost<span style="font-family:Arial,Helvetica,sans-serif">,在httppost 的建構函式中傳入待連線的地址</span> 3. 呼叫第一步中建立好的例項的 execute 方法來執行第二步中建立好的 method 例項 4. 讀 response 5. 釋放連線。無論執行方法是否成功,都必須釋放連線 */ public static String conResult, encrypt_app, encrypt_sign; public static String smsUrl = "http://192.168.0.140:8101/pismire/sfyan/syncAppData.lzyhjfs"; @Test public static void sendSms() throws Exception { //初始化httpclient HttpClient httpclient = new DefaultHttpClient(); //獲取httppost HttpPost httppost = new HttpPost(smsUrl); try { //新增引數 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("transdata",encrypt_app())); nameValuePairs.add(new BasicNameValuePair("sign", encrypt_sign())); //設定報文頭以及引數的格式 httppost.addHeader("Content-type","application/x-www-form-urlencoded"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); //執行post請求 HttpResponse response = httpclient.execute(httppost); //列印伺服器返回的狀態 System.out.println("伺服器返回的狀態:"+response.getStatusLine().getStatusCode()); // if (response.getStatusLine().getStatusCode() == 200) /** * 讀返回資料 * */ conResult = EntityUtils.toString(response.getEntity()); System.out.println(conResult); //斷開連線 httpclient.getConnectionManager().shutdown(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // return conResult; } /** * 拼接transdata資料 * */ public static String encrypt_app() throws Exception { int opertype = 1; String appid = "2001850000000320311"; String appname = "同步資料11"; String transdata = "{\"appid\":\"" + appid + "\",\"appname\":\""+ appname + "\",\"opertype\":" + opertype + "}"; encrypt_app = transdata; System.out.println("transdata:" + encrypt_app); return encrypt_app; } /** * 用MD5演算法對transdata進行加密 * */ public static String encrypt_sign() throws Exception { // sign簽名祕鑰,key1 和mod為後臺固定的祕鑰 BigInteger key1 = new BigInteger(EncryptorUtils.getDecryptionString("2SWUfsOjTTBpLfyWSNnXvvA37WLqvpUuOnIN9sjW6U4=")); BigInteger mod = new BigInteger(EncryptorUtils.getDecryptionString("+9mTlYq/DeqPDwNuvyuLI4eHw03rdP5w0O+bzb1uMcTASSC2AH381WeGO70wv9jm")); String desc = RSAUtil.encrypt(MD5.md5Digest(encrypt_app), key1, mod); encrypt_sign = desc; System.out.println("sign:" + encrypt_sign); return encrypt_sign; }
-----------------------TestNg執行完成輸出的日誌