且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AFNetworking在POST请求的JSON参数发送阵列

更新时间:2023-01-17 08:08:26

我没有看到你指定要张贴JSON,所以我打赌你发送表单URL参数编码,它是这样此,根据本AFHTTPClient文件:

I don't see where you're specifying you want to post JSON, so I'm betting you're sending Form URL Parameter Encoding, which goes like this, according to the AFHTTPClient documentation:

如果一个查询字符串对有一个的NSArray 为它的价值,阵列中的每个成员将被重新$ P格式psented $ 场[] =值1&放大器;场[] =值2 。否则,对将被格式化为字段=价值。重新串键和值的presentations使用 -description 法得出。构建查询串不包含?字符用来分隔查询组成部分。

If a query string pair has a an NSArray for its value, each member of the array will be represented in the format field[]=value1&field[]=value2. Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the -description method. The constructed query string does not include the ? character used to delimit the query component.

如果您的服务器确实期待您张贴JSON,在第二行添加此告诉AFNetworking是:

If your server is indeed expecting you to post JSON, add this on the second line to tell AFNetworking that:

// AFNetworking 1.0
// httpClient is a subclass of AFHTTPClient
httpClient.parameterEncoding = AFJSONParameterEncoding;

// AFNetworking 2.0
// httpClient is a subclass of AFHTTPRequestOperationManager or AFHTTPSessionManager
httpClient.requestSerializer = AFJSONRequestSerializer;

您会然后删除您的来电 NSJSONSerialization ,只是把 objectsInCart 参数字典。

You would then remove your call to NSJSONSerialization and just put objectsInCart into the parameters dictionary.

一个侧面说明:这是正常的子类 AFHTT prequestOperationManager AFHTTPSessionManager (AFNetworking 2.0)或 AFHTTPClient (AFNetworking 1.0),并把这种类型的配置,在你的 initWithBaseURL:方法。 (你可能不想旋转了一个新的客户端为每一个请求。)

A side note: it's normal to subclass AFHTTPRequestOperationManager or AFHTTPSessionManager (AFNetworking 2.0) or AFHTTPClient (AFNetworking 1.0) and put this type of configuration in your initWithBaseURL: method. (You probably don't want to spin up a new client for every request.)