JS里的POST方法如何设置cookie?

JS里的POST方法如何设置cookie?,第1张

如果这段POST代码和提交的目标页面不在同一个域,脚本是没权限给它设置cookies的,这是浏览器的基本保护措施。

如果是同一个域,直接在本页面设置cookies就行了,无需给POST数据包中插入cookies.

需求:模拟客户端进行post请求,除业务参数外,还需带有sign参数

在实现该需求时,使用了 requests.request()方法: requests.request('POST',url,data=rdata,cookies=rcookie),随后执行时遇到了以下问题:

原因:缺失了header相关信息

解决方法:在header中添加 User-Agent 和 refer等相关信息

原因:请求的body中,需以 json 形式传参,而初始调用时使用的为data

解决方法:解决方法有俩,

① 因为request() 参数中本来即存在 json,可直接使用json来传参,即:

requests.request('POST',url,json=json.dumps(rdata),cookies=rcookie)

② 也可继续使用 data 参数,此时需指定 content-type:

P.S. 若不指定content-type,data为dict时,默认为application/x-www-form-urlencoded

data为str时,则默认为application/json。

//发送post请求的同时传入cookie

+ (void)requestCookieWithPath:(NSString *)path

Params:(NSDictionary *)params

Method:(NSString *)method

Success:(HttpSuccessBlock)success{

//创建post请求

//创建AFHTTPClient对象

AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:kBaseUrl]]

NSMutableURLRequest *post = [client requestWithMethod:method path:path parameters:params]

NSData *cookiesData = [[NSUserDefaults standardUserDefaults]objectForKey:@"Set-Cookie"]

if ([cookiesData length]) {

NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesData]

NSHTTPCookie *cookie

for (cookie in cookies) {

[[NSHTTPCookieStorage sharedHTTPCookieStorage]setCookie:cookie]

}

}

//创建AFJSONRequestOperation对象

NSOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:post success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

success(JSON)

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

NSLog(@"error = %@",error)

//请求超时提示

NSString *errorStr = [[NSString alloc]initWithFormat:@"%@",error]

NSString *theError = @"The request timed out."

if ([errorStr rangeOfString:theError].length >0) {

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请求超时" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil]

[alert show]

}

}]

//开始请求

[operation start]

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11746378.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存