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

send HTTP PATCH request in iOS (Objective-c)

我正在使用 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;
}

[Error :Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x14e86d490 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}}]

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

中起作用

NSString *getURL = @"192.168.1.100/UpdateDeviceInfo/iPhone6/OS 9.2"

中好像有空格

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