如何调用ASP web api并从delphi 2007返回JSON

时间:2015-01-05 11:13:07

标签: delphi delphi-xe5 delphi-2007

我需要调用ASP web api并从delphi 2007返回JSON。我可以在带有TRestClient的RAD Studio XE 5中执行此操作。我试图把它放在一个DLL中,以便我可以从我的delphi 2007程序中调用它。但没有成功。我怎么能用delphi 2007做到这一点?

修改

这是我在delphi xe 5中尝试做的事情

class function TSampleApp.Hello(AModel: TModel): Integer;
var
  aRestClient: TRESTClient;
  aRestRequest: TRESTRequest;
  aRestResponse: TRESTResponse;
  aParam: TRESTRequestParameter;     
  jValue: TJSONValue;
  jObject: TJSONObject;
begin
  Result := -1;
  aRestClient := TRESTClient.Create(nil);
  try
    aRestResponse := TRESTResponse.Create(nil);
    try
      aRestRequest := TRESTRequest.Create(nil);
      try
        try          
          aRestClient.BaseURL := 'http://localhost:49272/api/test';
          aRestRequest.Client := aRestClient;
          aRestRequest.Response := aRestResponse;
          aRestRequest.Method := rmPOST;
          aRestRequest.Resource := 'hello';
          aParam := aRestRequest.Params.AddItem;
          aParam.Kind := pkREQUESTBODY;
          aParam.name := 'helloData';
          aParam.Value := TJson.ObjectToJsonString(AModel);

          aRestRequest.Execute;

          jValue := aRestResponse.JSONValue;
          jObject := TJSONObject.ParseJSONValue(jValue.ToString) as TJSONObject;
          Result := StrToIntDef((jObject.Get('status').JsonValue as TJSONString).Value, -1);
        finally
          FreeAndNil(jObject);
          FreeAndNil(jValue);
        end;
      finally
        FreeAndNil(aRestRequest);
      end;
    finally
      FreeAndNil(aRestResponse);
    end;
  finally
    FreeAndNil(aRestClient);
  end;
end;

此代码在win32 app中运行完美,但在“aRestResponse:= TRESTResponse.Create(nil);”上失败放入dll时。

1 个答案:

答案 0 :(得分:1)

我没有为delphi 2007找到其他客户端解决方案。我最终使用了indy。 我使用LkJson来处理json。

class function TSampleApp.Hello(AModel: TModel): Integer;
var
  idHttp: TIdHTTP;
  url, sjsonresponse, sjsonrequest: string;
  strRequest: TStrings;
  jsonObj: TlkJSONobject;
begin
  Result := -1;
  url := 'http://localhost:49272/api/test/hello';
  idHttp := TIdHTTP.Create;
  try
    jsonObj := TlkJSONobject.Create;
    try
      //populate
      jsonObj.Add('param1', AModel.param1);
      jsonObj.Add('param2', AModel.param2);
      sjsonrequest := TlkJSON.GenerateText(jsonObj);
    finally
      FreeAndNil(jsonObj);
    end;

    idHttp.Request.Accept := 'application/json';   
    strRequest := TStringList.Create;
    try
      strRequest.Values['helloData'] := sjsonrequest;
      sjsonresponse := idHttp.Post(url, strRequest);
    finally
      FreeAndNil(strRequest);
    end;

    jsonObj := TlkJSON.ParseText(sjsonresponse) as TlkJSONobject;
    try
      Result := StrToIntDef(VarToStr((jsonObj.Field['status'] as TlkJSONnumber).Value), -1);
    finally
      FreeAndNil(jsonObj);
    end;
  finally
    idHttp.Free;
  end;
end;

此代码也适用于dll。