Java HTTP Interface Endorsement, verification operation Method _java

Source: Internet
Author: User

1. Business background

Recently contacted some of the electrical business, found in the processing of electrical business interface, such as Taobao, payment interface, the interface between the two sides in order to ensure that data parameters in the transmission process has not been tampered with, the interface data need to be countersigned, and then the interface on the server side to verify the interface parameters, to ensure that two signatures are the same After the verification is passed, the business logic is processed. We mainly introduce the treatment of ideas, as for the signature algorithm I do not do too much introduction, online a lot.

2, processing ideas

The two sides agreed, the parameters in a specific order, such as in the first alphabetical order, such as url:http://xxx/xxx.do?a=wersd&b=sd2354&c=4&signature=xxxxxxxxxxxx ( Signature for the incoming signature), and so you get the entry, the parameter string a=wersd&b=sd2354&c=4 according to your agreed signature rules, you use MD5 to add a check, and then the signature value of the parameters in contrast to confirm the caller is legitimate, This is the idea of interface signature verification.

3. Practical Practice

Interface between the two sides through communication, the interface reached the following consensus:

1, attention, mainly refers to the interface of the protocol, incoming parameter types, signature algorithm, file format, and other instructions

2, the following is an electrical business interface of the real case, the two sides agreed to the interface URL, business parameters, fixed parameters, signature and return data format

When an interface is invoked, the interface caller code is as follows (for reference only):
Package com.pcmall;					
Import Java.io.BufferedReader;					
Import Java.io.DataOutputStream;					
Import java.io.IOException;					
Import Java.io.InputStreamReader;					
Import java.io.UnsupportedEncodingException;					
Import java.net.HttpURLConnection;					
Import Java.net.URL;					
Import Java.net.URLEncoder;					
Import Java.security.MessageDigest;					
Import java.security.NoSuchAlgorithmException;					
Import java.util.ArrayList;					
Import java.util.Collections;					
Import Java.util.Iterator;					
Import java.util.List;					
Import Java.util.Map;
					
Import Java.util.TreeMap;					
  public class Apitest {static String Test_url = "Pending";					
  static String Test_key = "Pending";					
  					
  static String test_sec = "Pending"; public static void Main (string[] args) throws Unsupportedencodingexception, nosuchalgorithmexception {String res					
    Ult = GetResult (Test_url, Getreqparam ());					
  System.out.print (result); } private static String GetreqpaRam () throws Unsupportedencodingexception, nosuchalgorithmexception {treemap<string, string> req = new Tree			
    Map<string, string> ();					
    Req.put ("A", test_key);					
    Req.put ("F", "JSON");					
    Req.put ("L", "ZH_CN");					
    Req.put ("M", "zhongan.repair.query");					
    Req.put ("V", "1.0");					
    Req.put ("I", "" "+ System.currenttimemillis ()/1000);					
    Req.put ("params", "{\" assignno\ ": \" test018\ "}");					
    					
    Req.put ("s", sign (req, NULL, test_sec));					
    StringBuilder param = new StringBuilder (); For (iterator<map.entry<string, string>> it = Req.entryset (). iterator (); It.hasnext ();)					
      {map.entry<string, string> e = It.next ();					
    Param.append ("&"). Append (E.getkey ()). Append ("="). Append (Urlencoder.encode (E.getvalue (), "UTF-8"));					
  Return param.tostring (). substring (1); private static String sign (map<string, string> paramvalues, List<String> Ignoreparamnames, String secret) throws NoSuchAlgorithmException, unsupportedencodingexception {S					
    Tringbuilder sb = new StringBuilder ();					
    list<string> paramnames = new arraylist<string> (Paramvalues.size ());					
    Paramnames.addall (Paramvalues.keyset ()); if (ignoreparamnames!= null && ignoreparamnames.size () > 0) {for (String Ignoreparamname:ignorep					
      Aramnames) {paramnames.remove (ignoreparamname);					
    					
    } collections.sort (Paramnames);					
    Sb.append (secret);					
    for (String paramname:paramnames) {sb.append (paramname). Append (Paramvalues.get (paramname));					
					
    } sb.append (Secret);					
    MessageDigest MD = messagedigest.getinstance ("SHA-1");					
  Return Byte2hex (Md.digest (Sb.tostring (). GetBytes ("UTF-8")); } private static String Byte2hex (byte[] bytes) {StringBuilder sign = new StringBuilder ();					
      for (int i = 0; i < bytes.length i++) {String hex = integer.tohexstring (Bytes[i] & 0xFF);					
      if (hex.length () = = 1) {sign.append ("0");					
    } sign.append (Hex.touppercase ());					
  return sign.tostring ();					
    private static string GetResult (string urlstr, string content) {URL url = null;					
    HttpURLConnection connection = null;					
      try {url = new URL (urlstr);					
      Connection = (httpurlconnection) url.openconnection ();					
      Connection.setdooutput (TRUE);					
      Connection.setdoinput (TRUE);					
      Connection.setrequestmethod ("POST");					
      Connection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded;charset=utf-8");					
      Connection.setusecaches (FALSE);					
      					
      Connection.connect ();					
      DataOutputStream out = new DataOutputStream (Connection.getoutputstream ()); Out.wRite (Content.getbytes ("UTF-8"));					
      Out.flush ();					
      					
      Out.close ();					
      BufferedReader reader = new BufferedReader (New InputStreamReader (Connection.getinputstream (), "UTF-8"));					
      StringBuffer buffer = new StringBuffer ();					
      String line = "";					
      while (line = Reader.readline ())!= null) {buffer.append (line);					
					
      } reader.close ();					
    return buffer.tostring ();					
    catch (IOException e) {e.printstacktrace ();					
      finally {if (connection!= null) {connection.disconnect ();					
  } return null; }	
  
  
}

The

Server-side code is as follows (for reference only):

@RequestMapping ("/repairtakeorder") @ResponseBody public Responsevo repairtakeorder (@RequestBody String jsonstr) {lo

		Gger.info ("Repairtakeorder Enter:" + jsonstr);
		Responsevo Responsevo = null;
			try {repairorder Repairorder = Jackjsonutil.tobean (Jsonstr, Repairorder.class);
			treemap<string, string> paramsmap = new treemap<string, string> ();
			Paramsmap.put ("gsxx01", repairorder.getgsxx01 ());
			Paramsmap.put ("OrderType", Repairorder.getordertype (). toString ());
			Paramsmap.put ("Serviceno", Repairorder.getserviceno ());
			Paramsmap.put ("Vipcard", Repairorder.getvipcard ());
			Paramsmap.put ("CustomerName", Repairorder.getcustomername ());
			Paramsmap.put ("Customerphone", Repairorder.getcustomerphone ());
			Paramsmap.put ("Customertel", Repairorder.getcustomertel ());
			Paramsmap.put ("Province", Repairorder.getprovince ());
			Paramsmap.put ("City", Repairorder.getcity ());
			Paramsmap.put ("County", Repairorder.getcounty ()); Paramsmap.put ("Address", RepairordeR.getaddress ());
			Paramsmap.put ("Salercode", Repairorder.getsalercode ());
			Paramsmap.put ("Salername", Repairorder.getsalername ());
			Paramsmap.put ("Storecode", Repairorder.getstorecode ());
			Paramsmap.put ("Storename", Repairorder.getstorename ());

			Paramsmap.put ("Site", Repairorder.getsite ());
			Paramsmap.put ("Sitedesp", Repairorder.getsitedesp ());
			Paramsmap.put ("Engineercode", Repairorder.getengineercode ());
			Paramsmap.put ("Engineername", Repairorder.getengineername ()); if (repairorder.getservicedate ()!= null) {paramsmap.put ("ServiceDate", Dateutils.formatdate (Repairorder.getser
			Vicedate ())); } if (Repairorder.getsaleprice ()!= null) {paramsmap.put ("Saleprice", Repairorder.getsaleprice (). ToString (
			));
			} paramsmap.put ("Profitcenter", Repairorder.getprofitcenter ());
			Paramsmap.put ("CostCenter", Repairorder.getcostcenter ());
			Paramsmap.put ("gsxx02", repairorder.getgsxx02 ()); Paramsmap.put ("Returnreason", Repairorder.getreturnreaSon ());
			if (Repairorder.getoriorder ()!= null) {paramsmap.put ("Oriorder", Repairorder.getoriorder (). toString ());
			} if (Repairorder.getoriserviceno ()!= null) {paramsmap.put ("Oriserviceno", Repairorder.getoriserviceno ());
			////concatenation signed original string (a=1&b=2) String paramsrc = Requestutils.getparamsrc (Paramsmap);
			Logger.info ("Signature of the original string:" + paramsrc); Check the operation if (Signutils.verifymd5 (PARAMSRC, Repairorder.getsign ())) {//Process business logic Responsevo=erpserviceimpl.repairt
				
			Akeorder (Repairorder);
				else {Responsevo = new Responsevo ();
				Responsevo.setsuccess (FALSE);
			Responsevo.seterrormsg ("Verification Failure");
			The catch (Exception e) {logger.error ("", e);
			Responsevo = new Responsevo ();
			Responsevo.setsuccess (FALSE);
		Responsevo.seterrormsg (Stringutils.isnotblank (E.getmessage ()) E.getmessage (): "Background exception");

	return Responsevo; }

Above this Java HTTP interface to sign, check the operation method is small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.