swift - 我很新,面临发送 api 请求的问题
问题描述
我对 swift 还很陌生,我正面临 Alamofire 的问题,我正在尝试发送一个带有 json 正文的 get 请求,但我的代码被困在这里:
struct request {
func getMessage(message:String){
let parameters: [String:Any] = [
"message" : [
"text": message,
"type":"text"
],
"type":"message",
"recipentId":"",
"info": [
"token":""
]
]
makeRequest(parameters: parameters)
}
func makeRequest(parameters:[String:Any]){
AF.request("https://bot.ortus4c.com/api/botController/token/5cc1f42e66d0ba0001dbf944",method: .post,parameters: parameters).response{
response in
debugPrint(response)
}
}
执行此代码后,我得到:
[Request]: POST https://bot.ortus4c.com/api/botController/token/5cc1f42e66d0ba0001dbf944
[Request Body]:
info%5Btoken%5D=&message%5Btype%5D=text&message%5Btext%5D=Karakter&recipentId=&type=message
[Response]:
[Status Code]: 415
[Headers]:
Accept: application/json
Content-Length: 0
Date: Sat, 07 Mar 2020 19:10:23 GMT
Server: cloudflare
cf-cache-status: DYNAMIC
cf-ray: 57069dc3eaccad06-OTP
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
x-b3-traceid: b10ba988c0249901
[Response Body]:
None
[Data]: None
[Network Duration]: 0.3303520679473877s
[Serialization Duration]: 0.0s
[Result]: success(nil)
与我通过邮递员发送此请求时所期望的相比,我没有得到任何结果正文:
"result": {
"messages": [
{
"type": "text",
"text": "Karakter Analizine Hoşgeldiniz. Analize başlamak için \"karakter\" yazınız"
},
{
"type": "text",
"text": "Test"
}
],
"tag": [
"start",
"finish"
],
"conversation_id": "5e63f302dc4bec0001883f01",
"intent_name": "Default Karakter",
"intent_id": "5ccb46ef66d0ba0001dbfcdf",
"intent_score": null,
"current_flow_id": "ee52db21-dae1-4587-80cd-7649798dddce1583608578222"
}
那么我如何使用下面的给定正文发送此帖子请求:
let parameters: [String:Any] = [
"message" : [
"text": message,
"type":"text"
],
"type":"message",
"recipentId":"",
"info": [
"token":""
]
]
现在我已经发送了请求并得到了一个如下所示的正文:
"result": {
"messages": [
{
"extra": {},
"question": "Adınız ?",
"type": "text",
"values": [
{
"text": ""
}
],
"askCount": 1,
"text": "Adınız ?",
"waitUserInput": true
}
],
"tag": [
"start",
"p_firstName",
1
],
"conversation_id": "5e63ffa0dc4bec0001883f10",
"intent_name": "Karakter Analizi",
"intent_id": "5cc20ae266d0ba0001dbf946",
"intent_score": "62.0",
"current_flow_id": "62ac3ac8-0cd7-43e5-b92b-f119d49c40d41583611808850"
}
如何将问题变量打印到屏幕上的标签上?
解决方案
响应代码 415 表示响应Unsupported Media Type
的Accept
标头让您知道服务器希望数据以JSON
. 您所要做的就是让 Alamofire 知道它应该像JSON
在请求正文中一样编码参数
AF.request("https://bot.ortus4c.com/api/botController/token/5cc1f42e66d0ba0001dbf944",
method: .post,
parameters: parameters,
encoding: JSONEncoding.default).response { response in
debugPrint(response)
}
推荐阅读
- ios - 自动布局不适用于 Plus 型号
- ios - 尽管有条件声明,Segue 仍然通过
- css - jquery 使默认导航栏按钮处于活动状态
- visual-studio - Visual Studio 元数据文件名不一致
- c# - C# Azure 存储 - 如何将文件上传到已经存在的容器
- r - 使用 Rccp 将数据框中的列传递给函数
- c++ - 标准库标识符与用户标识符冲突
- python - 用正则表达式组的字典替换Python字符串模板?
- python - 这个错误'int'对象不可调用阻碍了我
- mysql - “com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链路故障”