Delphi / 控件 · 2024年10月15日

NetHTTPClient使用

传输 multipart/form-data 数据;utf8编码

procedure TForm1.Button1Click(Sender: TObject);
var
  http: TNetHTTPClient;
  parts: TMultipartFormData;
  resp: TStringStream;
begin
  if OpenDialog1.Execute then
  begin
    http := TNetHTTPClient.Create(nil);
    parts := TMultipartFormData.Create;
    resp := TStringStream.Create('', TEncoding.GetEncoding(65001));
    try
      parts.AddField('fieldname', 'fieldvalue');
      parts.AddFile('fname', OpenDialog1.FileName);
      http.ConnectionTimeout := 2000; // 2秒
      http.ResponseTimeout := 10000; // 10秒
      http.AcceptCharSet := 'utf-8';
      http.AcceptEncoding := '65001';
      http.AcceptLanguage := 'zh-CN';
      http.ContentType := 'multipart/form-data';
      http.UserAgent := 'Embarcadero URI Client/1.0';
      try
        Memo1.Lines.Add('尝试上传文件 ' + OpenDialog1.FileName);
        http.Post('https://www.offeu.com/upfile', parts, resp);
        Application.ProcessMessages;
      except
        on E: Exception do            // Error sending data: (12002) 操作超时.
            // Error receiving data: (12002) 操作超时
          if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error sending data' then
            Memo1.Lines.Add('Error:连接失败!')
          else if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error receiving data' then
            Memo1.Lines.Add('Error:接收失败,请延长接收超时时间!')
          else
            Memo1.Lines.Add('Error:' + E.Message);
      end;
      Memo1.Lines.Add(resp.DataString);  //输出返回
    finally
      http.Free;
      resp.Free;
      parts.Free;
    end;
  end;
end;
Pascal

传输 body json格式; utf8编码

function NetHttpPost(AURL:string; AInJson:string; var AOutJson:string):Boolean;
var
  _NetHttpClient : TNetHTTPClient;
  _Request, _Response: TStringStream;
  _IHTTPResponse : IHTTPResponse;
begin
  AOutJson := '';
  Result := False;
  _NetHttpClient := TNetHTTPClient.Create(nil);
  _Request := TStringStream.Create(AInJson, TEncoding.GetEncoding(65001));
  _Response := TStringStream.Create('', TEncoding.GetEncoding(65001));
  try
    try
      GBusiness.AddLog(Format('[Device] Http Request - Url %s - Body %s',[AURL, AInJson]), llAlert);
      with _NetHttpClient do
      begin
        ConnectionTimeout := 2000;
        ResponseTimeout   := 5000;
        AcceptCharSet := 'utf-8';
        AcceptEncoding := '65001';
        AcceptLanguage := 'zh-CN';
        ContentType := 'application/json';
        UserAgent := 'Embarcadero URI NetHttpClient/1.0';
        _IHTTPResponse := Post(AURL, _Request, _Response);
        if _IHTTPResponse.StatusCode = 200 then
        begin
          AOutJson := _Response.DataString;  //输出返回值
          Result := True;
        end
        else
        begin
          AOutJson := format('{"code":%d,"data":null,"msg":"%s"}',
                              [_IHTTPResponse.StatusCode,
                               _IHTTPResponse.StatusText]);
        end;
        GBusiness.AddLog(Format('[Device] Http Response - %s',[AOutJson]), llAlert);
      end;
    except
      on E: Exception do
      begin
        AOutJson := format('{"code":999,"data":null,"msg":"%s"}', [E.Message]);
        GBusiness.AddLog(Format('[Device] Http Response Err - %s',[E.Message]), llAlert);
        GSystemLog.AddLog(Format('NetHttpPost Err - %s - Url %s - Body %s', [E.Message, AURL, AInJson]));
      end;
    end;
  finally
    _NetHttpClient.Destroy;
    _Request.Destroy;
    _Response.Destroy;
  end;
end;
Pascal