Delphi7 's new life, participating in distributed application development, invoking the application of restful Api,json

Source: Internet
Author: User
Tags http post

Objective:

1, the company Delphi7 development of the traditional software is still alive well, but we all know that Delphi has already sunset, now become a backward, followers. Carefully forget already 6, 7 No. The new Delphixe7, there is no time cost to adapt and research.

Because of the large number of use of 3rd party components and controls, want to upgrade estimates are thankless things ...

2, keep the original code, develop new features can call the remote host (cloud host) rest ful-style API, using JSON to exchange data. This will catch up with the new trend, the resurrection.

As a result of online search many times, found to meet the needs of the article very few, recorded here, give people to fish bar.

    • Delphi7 using JSON
    • DELPHI7 uses MSXML's "ixmlhttprequest" object implementation to initiate an Http post GET request and pass the JSON.
    • Delphi7 using base64 encoded images to pass through JSON

Here's the key code:

(1) Msxml,superobject (3rd party, Delphi7 not own), ENCDDECD reference

(2) Use of XMLHttpRequest:

Submit Membership card Information Procedure Tformmakecard.btnokclick (sender:tobject);     var url:string;          Resultjson,paramsjson:isuperobject;begin if (checkinput) THEN begin httpreq: = Coxmlhttprequest.create; Two ways to submit a request: Get and Post,get are passed by URL address parameter if it is Chinese need to transcode, need to add timestamp post does not need to add timestamp//get url: = ' http://localhost:5269/a          Pi/webmemberapi/newmemberregister?timestamp= ' +inttostr (windows.gettickcount);          URL: = ' http://localhost:5269/api/webmemberapi/NewMemberRegister? ';          Httpreq.open (' Post ', url, False, Emptyparam, Emptyparam);          HTTP Post httpreq.setrequestheader (' Accept ', ' Application/json ');          Httpreq.setrequestheader (' Content-type ', ' Application/json ');            Request Body Try paramsjson:= getmemberentity ();            Memo1.Lines.Clear; Memo1.            Text: = Paramsjson.asstring ();            Httpreq.send (Paramsjson.asstring ());            Resultjson:=so (Httpreq.responsetext); if (Resultjson<>nil) theN Begin showmessage (resultjson.s[' Message ');                         The card is successful, if there is a photo or signature, perform the upload if (resultjson.b[' Success ']=true) THEN BEGIN if (mbphoto) THEN BEGIN URL: = ' Http://localhost:5269/api                                /webmemberapi/uploadmemberimage? ';                                Httpreq.open (' Post ', url, False, Emptyparam, Emptyparam);                                HTTP Post httpreq.setrequestheader (' Accept ', ' Application/json ');                                Httpreq.setrequestheader (' Content-type ', ' Application/json ');                                Paramsjson:=so ();                                paramsjson.s[' imagefilecontent ']:= bitmaptostring (IMAGEMEMBERPHOTO.PICTURE.BITMAP);                                paramsjson.s[' imagecategory ']:= ' Avatar ';  paramsjson.s[' Membercardno ']:=self.edtcardno.text;                              Httpreq.send (Paramsjson.asstring ());                            Resultjson:=so (Httpreq.responsetext);                         End if (mbsign) THEN BEGIN URL: = ' http://localhost:5269/api/webmemb                                Erapi/uploadmemberimage? ';                                Httpreq.open (' Post ', url, False, Emptyparam, Emptyparam);                                HTTP Post httpreq.setrequestheader (' Accept ', ' Application/json ');                                Httpreq.setrequestheader (' Content-type ', ' Application/json ');                                Paramsjson:=so ();                                paramsjson.s[' imagefilecontent ']:= bitmaptostring (IMAGEMEMBERSIGN.PICTURE.BITMAP);                                paramsjson.s[' imagecategory ']:= ' signature ';                                paramsjson.s[' Membercardno ']:=self.edtcardno.text; HtTpreq.send (Paramsjson.asstring ());                            Resultjson:=so (Httpreq.responsetext);                      End               End          End          Except on Ex:exception do ShowMessage (ex.message);       End End;end;

XMLHttpRequest instantiation

Httpreq: = coxmlhttprequest.create;
Two ways to submit a request: Get and Post,get are passed by URL address parameter if the Chinese need to transcode, need to add timestamp post does not need to add timestamp
Get URL: = ' http://localhost:5269/api/webmemberapi/NewMemberRegister?timestamp= ' +inttostr (windows.gettickcount) ;
URL: = ' http://localhost:5269/api/webmemberapi/NewMemberRegister? ';

Post or get
Httpreq.open (' Post ', url, False, Emptyparam, Emptyparam);
HTTP POST * * This is the key code **requestheader settings ' Application/json ', the server side can be recognized as JSON
Httpreq.setrequestheader (' Accept ', ' Application/json ');
Httpreq.setrequestheader (' Content-type ', ' Application/json ');

This is the subject of the request

Httpreq.send (Paramsjson.asstring ());

Deserializes the JSON string returned by the server into a Superobject object.

Resultjson:=so (Httpreq.responsetext);

Using system;using system.collections.generic;using system.linq;using system.web;namespace com.aidpoint.memberapi.models{//<summary>//    action return value entity///    </summary>    Public Class Apiactionresult    {public        bool Success        {            get;            Set;        }        public string Message        {            get;            Set;        }        public Object Result        {            get;            Set;}}    }

if (Resultjson<>nil) then
Begin
ShowMessage (resultjson.s[' Message ');
Successful card issuance, if there is a photo or signature to perform the upload
if (resultjson.b[' Success ']=true) then ...

End

(3) JOSN contains base64 encoded images:

//bitmap file goto Base64 stringfunctionTformmakecard.bitmaptostring (IMG:TBITMAP):string;varMs:tmemorystream;  Ss:tstringstream; S:string;beginMS:=tmemorystream.create; Img.    Savetostream (MS); SS:= Tstringstream.create ("'); Ms. Position:=0; Encodestream (MS,SS);//encode the memory stream as a stream of base64 characterss:=SS.    datastring; Ms.    Free; Ss.    Free; Result:=s;End; URL:='http://localhost:5269/api/webmemberapi/UploadMemberImage?'; Httpreq.open ('Post', URL, False, Emptyparam, Emptyparam); //HTTP POSTHttpreq.setrequestheader ('Accept','Application/json'); Httpreq.setrequestheader ('Content-type','Application/json'); Paramsjson:=So (); paramsjson.s['imagefilecontent']:=bitmaptostring (IMAGEMEMBERPHOTO.PICTURE.BITMAP); paramsjson.s['imagecategory']:='Avatar'; paramsjson.s['Membercardno']:=Self.edtCardNo.Text;                                Httpreq.send (Paramsjson.asstring ()); Resultjson:=so (Httpreq.responsetext);

(4) server-side Web API

 Public Apiactionresult newmemberregister ([frombody]memberdto memberdto) {//Initialize return value var Resul t = new Apiactionresult () {Success = false, Result = null, MESSAG E = "Operation failed.            "            }; if (memberdto! = null) {try {using (memberentities db = new                        Memberentities ()) {var dbentity = checkmemberexists (memberdto, DB); if (dbentity==null) {//INSERT member Table VA                            R entity = dto2entity.converttoentityobject< Membership table > (memberdto) as membership form; Db.                            AddTo Membership Form (entity);                            Generate stored value Flow--w: False Receive, D: Points redemption gift, F: New card, C: Stored value, Q: Withdrawal, J: Points consumption record var detailrec = new Member Stored value water table ();                            Detailrec. Membership card number = Memberdto. Card number; Detailrec. Stored valueFlag = "F";                            Detailrec. Recharge amount = memberdto. Open card amount. Value;                            Detailrec. New card = "Y"; Db.                            AddTo member Stored Value water table (DETAILREC); try {db.                                SaveChanges (); Result.                                Success = true; Result.                                Result = entity; Result. Message = string. Format ("Operation succeeded. New card [{0}], open card amount: {1}.                            ", entity. Self-numbering, entity. Open card amount); } catch (Exception ex) {var Exx = ex . InnerException = = null? Ex:ex.                                innerexception; throw new Exception (Exx.                            Message);                            }} else { Result.                            Success = false; Result. Result = null; Result. Message = string. Format ("card number [{0}] already exists. Card Issuing store [{1}], cardholder: {2}.                                                ", dbentity. Self-numbering, dbentity. Issuing branch number, dbentity. Name); }}} catch (Exception ex) {var Exx = Ex. InnerException = = null? Ex:ex.                    innerexception; Result.                    Success = false; Result.                    Result = Exx; Result. Message = string. Format ("Operation exception, exception message: {0}.") ", Exx.                Message);        }} return result; }

  

  

  

Delphi7 's new life, participating in distributed application development, invoking the application of restful Api,json

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.