Curl -d到Alamofire [英] Curl -d to Alamofire

查看:329
本文介绍了Curl -d到Alamofire的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关注此页面( https:// django- oauth-toolkit.readthedocs.org/en/latest/rest-framework/getting_started.html ),我可以为我的django项目设置OAuth。



以下curl命令为我提供了一个访问资源的令牌。

  curl -X POST 
-dgrant_type = password& username =< user_name>& password =< password>
-u< client_id>:< client_secret>但是,当我使用Alamofire发送请求时,我们可以通过使用Alamofire来发送请求,但是当我使用Alamofire发送请求时,会发生这种情况:http:// localhost:8000 / o / token /
  Alamofire.request(.POST,url,parameters:parameters,encoding:.JSON)
.authenticate(user:client_ID,password:client_Secret)

其中parameter是字典

b
$ b

  [
password:< password> ;,
grant_type:password,
username :< username>
]

使用curl命令,我可以从Django看到request.POST.items )返回参数列表。但是,使用Alamofire,没有什么。参数出现在request.body中!



这个问题让我疯狂。任何帮助将感激!



提前感谢。

解决方案

好吧,你的curl命令发布为 Content-Type:application / x-www-form -urlencoded 格式,而你是强制发布为json( .JSON )。因为这个原因,请求已经作为 application / json 传递给你的django,你看到的参数在body而不是 POST.items()



因此请从您的代码中删除 encoding:.JSON


Following this page (https://django-oauth-toolkit.readthedocs.org/en/latest/rest-framework/getting_started.html), I was able to setup OAuth for my django project.

The following curl command gives me a token to access resource.

curl -X POST 
-d "grant_type=password&username=<user_name>&password=<password>" 
-u"<client_id>:<client_secret>" http://localhost:8000/o/token/

However, when I send request using Alamofire, things are a bit strange. This is my code

Alamofire.request(.POST, url, parameters: parameters, encoding: .JSON)
         .authenticate(user: client_ID, password: client_Secret)

where parameter is a dictionary

[
 "password": <password>, 
 "grant_type": password, 
 "username": <username>
]

Using curl command, I can see from Django that request.POST.items() returns the list of parameters. However, using Alamofire, there is nothing. The parameters appeared in request.body instead!

This problem is driving me crazy. Any help will be grateful!

Thanks in advance.

解决方案

Well, your curl command is posting as Content-Type: application/x-www-form-urlencoded format, whereas you are forcing to post as json (.JSON). For this reason the request has passed as application/json to your django and you are seeing the parameter in body instead of POST.items().

So remove this from your code encoding: .JSON.

这篇关于Curl -d到Alamofire的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆