【问题标题】:translate curl command into NSMutableUrlRequest将 curl 命令翻译成 NSMutableUrlRequest
【发布时间】:2013-02-01 22:45:09
【问题描述】:

我正在尝试移植 curl 请求:

curl -X POST -H [header stuff]  -d '{"key":"value"}' [host] 

进入一个 NSMutableUrlRequest。到目前为止,我已经去掉了工作正常的部分,只保留了给我带来麻烦的部分,即 -d '{"key":"value"}'。其他标题部分很好。

根据curl手册-d表示payload是以application/x-www-form-urlencoded格式发送的,所以我做了以下操作:

    NSString* post =   @"{\"key\":\"value\"}";
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    [_request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [_request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [_request setHTTPMethod:@"POST"];
    [_request setHTTPBody:postData];

这会返回以下错误

失败并出现错误 Error Domain=AFNetworkingErrorDomain Code=-1011 “预期状态代码在 (200-299),得到 400” UserInfo=0xa363550 {NSLocalizedRecoverySuggestion={"code":107,"error":"bad www-form -urlencoded 数据"}

谁能指出我调试这些东西的正确方向? -A

【问题讨论】:

    标签: ios web-services nsmutableurlrequest


    【解决方案1】:

    Content-Type 应该是 application/json 或者可能是 text/plain。如果一切都失败了,试试application/octet-stream(原始二进制数据)。

    【讨论】:

    • 解决方案适用于那些感兴趣的人 [_request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    猜你喜欢
    • 2017-12-20
    • 2017-06-10
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多