【问题标题】:How can I do a POST call to my api with JSONHTTPClient?如何使用 JSON HTTPClient 对我的 api 进行 POST 调用?
【发布时间】:2017-04-28 18:54:57
【问题描述】:

我在我的 Objective c 应用程序中使用来自 github 的 JSONHTTPClient 库。我对我的 api 进行了很多调用并且一切正常,但是当我尝试添加带有标题和正文的 POST 函数时,我收到一个错误:

Error Domain=JSONModelErrorDomain Code=2 "网络响应错误。 JSON URL 可能无法访问。” UserInfo={NSLocalizedDescription=网络响应错误。大概是 JSON URL 无法访问。}

我使用 JSONFromURLWithString url 进行 POST 调用。 api调用正常工作,从服务器返回数据(我从邮递员那里测试过)但是从我的目标c应用程序中的这个函数我总是得到错误,为什么不得到响应?

我是否发送了任何格式错误的数据?

这是我的代码:

NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"var1", @"keyVar1", @"5" , @"keyvar2",  nil];//Here initialize my headers values into a dictionary

NSDictionary *dicty = [NSDictionary dictionaryWithObjectsAndKeys:@"6234", @"id", @"4324" , @"id2", nil];//This is my body
NSData *jsonDatass = [NSJSONSerialization dataWithJSONObject:dicty options:0 error:nil];//Here convert my body to nsdata

[JSONHTTPClient JSONFromURLWithString:@"myURL" method:@"POST" params:nil orBodyData:jsonData headers:parameters completion:^(id json, JSONModelError *err){

        NSLog(@"have error?: %@", err);
        NSLog(@"have response?: %@", json);

    }];

【问题讨论】:

    标签: ios objective-c json post jsonhttpclient


    【解决方案1】:

    我认为首先要在 url 中传递 json,您需要将 json 转换为字符串,然后将字符串作为参数传递。这就是为什么在邮递员中它运作良好的原因。
    我想知道你们加入后的完整网址,在

      [JSONHTTPClient JSONFromURLWithString:@"myURL" method:@"POST" params:nil 
     orBodyData:jsonData headers:parameters completion:^(id json, JSONModelError *err){
      } 
    


    方法,您的完整网址应与

    ******************************** divider ***********************************

    NSString *myString = [[NSString alloc] initWithData:jsonDatass encoding:NSUTF8StringEncoding];
    myString = [myString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *uploadUrl = [NSString stringWithFormat:@"<YOU host URL>"?data=%@",myString];
    

    还有parameters应该转成字符串拼接到url中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多