在iOS中发送HTTP PATCH请求(Objective-c)

时间:2016-01-20 14:17:49

标签: ios objective-c http postman nsmutableurlrequest

我正在使用REST API,其中一个api是PATCH,我尝试使用以下代码调用它,但它会抛出错误,而同样的api在Postman客户端中工作。

+ (NSURLSessionTask *)callPATCHAPIWithAPIName:(NSString *)apiName andCompletionHandler:(void(^)(id result, NSInteger responseCode, NSError *error))completionHandler
{
    NSString *getURL = @"192.168.1.100/UpdateDeviceInfo/iPhone6/OS 9.2";
    NSURL *URL = [NSURL URLWithString:getURL];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];

    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfiguration.timeoutIntervalForRequest = 45.0f;

    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];

    // Create Data from request
    NSData *requestData = [NSData dataWithBytes: [@"" UTF8String] length:[@"" length]];

    [request setHTTPMethod:@"PATCH"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];

    [request setHTTPBody:requestData];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error)
                                  {
                                      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;

                                      NSInteger responseCode = [httpResponse statusCode];
                                      NSLog(@"response Code : %ld",(long)responseCode);
                                  }];

    [task resume];
    return task;
}
  

[错误:错误域= NSURLErrorDomain代码= -1002“不支持的URL”UserInfo = {NSLocalizedDescription =不支持的URL,NSUnderlyingError = 0x14e86d490 {错误域= kCFErrorDomainCFNetwork代码= -1002“(null)”}}]

我在查询字符串中传递参数,而不是在请求正文中。虽然同样的事情在Postman客户端&机器人。

1 个答案:

答案 0 :(得分:4)

好像你在NSString *getURL = @"192.168.1.100/UpdateDeviceInfo/iPhone6/OS 9.2"

中有一个空格

我不相信网址格式支持空格!相反,如果需要空格,请确保使用getURL = [getURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];来处理url字符串中的空格!