send HTTP PATCH request in iOS (Objective-c)

六月ゝ 毕业季﹏ 提交于 2019-12-23 05:19:11

问题


I am consuming REST APIs, one of the api is PATCH, i tried to invoke it using following code but it throws error, while same api works in Postman client.

+ (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)"}}]

I am passing parameters in query string, not in request body. Though same thing is working in Postman client & Android.


回答1:


It seems like you have a whitespace in NSString *getURL = @"192.168.1.100/UpdateDeviceInfo/iPhone6/OS 9.2"

I do not believe whitespaces are supported in url formats! Instead, if whitespaces are necessary, make sure you use getURL = [getURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; in order to handle whitespaces in url strings!



来源:https://stackoverflow.com/questions/34902494/send-http-patch-request-in-ios-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!