如何保存cookie?

如何保存cookie

阅读 573
avatarAI BotBETA

保存cookie的步骤主要包括以下几步:

  1. 创建一个cookie对象,并设置其名称和值。例如:
cookie = new Cookie("cookieName", "cookieValue");
  1. 设置cookie的过期时间。例如:
cookie.setMaxAge(60 * 60 * 24); // 设置cookie的过期时间为一天,单位为秒
  1. 将cookie添加到response中,发送给客户端。例如:
response.addCookie(cookie);
  1. 在客户端中保存cookie。当浏览器接收到服务器发送的cookie后,会将cookie保存到本地。下次浏览器再次访问该网站时,会自动将cookie发送给服务器。

注意:为了安全起见,应该使用HTTPOnly属性来防止跨站脚本攻击。例如:

cookie.setHttpOnly(true);
1 个回答

本地保存cookie可使用用户首选项。

示例代码

// xxx.ets 
import { BusinessError } from '@ohos.base'; 
import { preferences } from '@kit.ArkData'; 
import { promptAction } from '@kit.ArkUI'; 
 
@Entry 
@Component 
struct Index { 
  preferences: preferences.Preferences | null = null; 
  @State cookie: string = ''; 
 
  async aboutToAppear() { 
    // 获取Preferences实例 
    this.preferences = await preferences.getPreferences(getContext(this), 'myStore'); 
  } 
 
  putPreference() { 
    // 将数据写入缓存的Preferences实例中 
    this.preferences?.put('cookie', this.cookie); 
    // 通过flush将Preferences实例持久化 
    this.preferences?.flush(); 
  } 
 
  getPreference() { 
    // 从缓存的Preferences实例中获取键对应的值 
    this.preferences?.get('cookie', '', (err: BusinessError, val: preferences.ValueType) => { 
      this.cookie = val.toString(); 
    }) 
  } 
 
  build() { 
    Column({ space: 15 }) { 
      Text(`Cookie:${this.cookie}`) 
        .width('95%') 
      TextInput({ placeholder: '请输入Cookie', text: this.cookie }) 
        .showUnderline(true) 
        .width(380) 
        .onChange((value: string) => { 
          this.cookie = value; 
        }) 
      Button('保存Cookie', { type: ButtonType.Normal, stateEffect: true }) 
        .borderRadius(8) 
        .backgroundColor(0x317aff) 
        .width(90) 
        .onClick(() => { 
          this.putPreference(); 
        }) 
      Button('读取Cookie', { type: ButtonType.Normal, stateEffect: true }) 
        .borderRadius(8) 
        .backgroundColor(0x317aff) 
        .width(90) 
        .onClick(() => { 
          this.getPreference(); 
        }) 
    } 
  } 
}

参考链接

@ohos.data.preferences (用户首选项)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进