新手,高分求問:
報文示例如下{"image_content":"圖片的base64內容","id":"12345678",}
介面方法http(post)方式,請求body是json
請問怎么用delphi實作,給個代碼吧,謝謝
uj5u.com熱心網友回復:
function TWebAPI_JSON.Pic_Update(ABase64Img: String; var APic: TPic; var AErrStr: String; ARsultErrMsg: Boolean = False): Boolean;function CreateIdHttp: TCustomIndyHttp;
begin
Result := TCustomIndyHttp.Create(nil);
Result.AllowCookies := true;
Result.HandleRedirects := true; // 允許頭轉向
Result.ReadTimeout := 5000; // 請求超時設定
Result.ConnectTimeout := 15000;
Result.Request.ContentType := 'application/json'; // 設定內容型別為jso
Result.Request.Accept := 'application/json';
end;
const
// URL = '/picasso-wan/governance-api/v1/file_upload.json';
URL = 'http://..........';
JSONStr = '{ "fileStr": "string"}';
var
AJSon, AResult: ISuperObject;
SendJSONStream: TStringStream;
AResultStr: string;
AIdhttp: TCustomIndyHttp;
AItem: TSuperArray;
begin
AIdhttp := CreateIdHttp;
AIdhttp.ConnectTimeout := 15000;
AIdhttp.ReadTimeout := 15000;
AJSon := SO(JSONStr);
Result := False;
AJSon.S['id'] :='12345678';
AJSon.S['image_content'] := '圖片的base64內容';
SendJSONStream := TStringStream.Create(UTF8Encode(AJSon.AsString));
try
try
AResultStr := AIdhttp.Post(FHostURL + URL, SendJSONStream);
AResult := SO(AResultStr);
if AResult.b['success'] then
begin
if Assigned(AResult['collection']) then
begin
AItem := AResult['collection'].AsArray;
if AItem.Length > 0 then
begin
APic.fileUrl := AItem[0]['fileUrl'].AsString;
APic.fileUrl := StringReplace(APic.fileUrl, '.jpg.jpg', '.jpg', [rfReplaceAll, rfIgnoreCase]);
end;
Result := True;
end;
AErrStr := '無資料回傳';
end;
except
on e: EIdHTTPProtocolException do
begin
AResultStr := e.ErrorMessage;
AResult := SO(AResultStr);
if Assigned(AResult['message']) then
begin
AErrStr := AResult['message'].AsString;
end
else
begin
if not ARsultErrMsg then
AErrStr := GetErrStr(e)
else
AErrStr := e.Message;
end;
end;
on e: Exception do
begin
if not ARsultErrMsg then
AErrStr := GetErrStr(e)
else
AErrStr := e.Message;
end;
end;
finally
AIdhttp.Free;
SendJSONStream.Free;
end;
end;
uj5u.com熱心網友回復:
procedure PostImage;
var
jsonObj: TJsonObject;
IdHttp: TIdHTTP;
postData: UTF8String;
resp: string;
reqStm: TStringStream;
begin
reqStm := TStringStream.Create('');
try
jsonObj := TJsonObject.Create;
try
jsonObj.AddPair('image_content','圖片的base64內容');
jsonObj.AddPair('id','12345678');
postData := UTF8Encode(jsonObj.ToString);
reqStm.WriteBuffer(BytesOf(postData), Length(postData));
finally
FreeAndNil(jsonObj);
end;
IdHttp := TIdHTTP.Create;
try
try
IdHttp.AllowCookies := True;
IdHttp.ConnectTimeout := 30000;
IdHttp.Request.ContentType := 'application/json;charset=UTF-8';
IdHttp.Request.Accept := '*/*';
resp := IdHttp.Post('你的URL', reqStm);
if IdHttp.ResponseCode = 200 then
begin
//你的處理
end;
except ON E:Exception do
end;
finally
FreeAndNil(IdHttp);
end;
finally
FreeAndNil(reqStm);
end;
end;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/39551.html
標籤:網絡通信/分布式開發
