ios - NSURLRequest with HTTP Authentication -
i trying authenticate http restful site using nsurlrequest iphone app. put user/pass encoded in base64 , pass in "authorization" header in nsurlrequest word "basic " appended it. however, keep getting auth error in other end. here code. if manual curl request, works. checked make sure base64 encoded , user, pass, , url correct.
nsmutableurlrequest *urlrequest = [[nsmutableurlrequest alloc] initwithurl:[nsurl urlwithstring:url]]; nsstring *basicauthcredentials = [nsstring stringwithformat:@"%@:%@", user, pass]; nsstring *authvalue = [nsstring stringwithformat:@"basic %@", afbase64encodedstringfromstring(basicauthcredentials)]; authvalue = [authvalue stringbyreplacingoccurrencesofstring:@"\n" withstring:@""]; [urlrequest setvalue:authvalue forhttpheaderfield:@"authorization"]; [urlrequest sethttpmethod: @"get"]; nsdata *httpdata = [self encodedictionary:data]; [urlrequest sethttpbody:httpdata]; nshttpurlresponse *response; nserror *error; nsdata* result = [nsurlconnection sendsynchronousrequest:urlrequest returningresponse:&response error:&error];
the auth code looks fine. sure, stringbyreplacingoccurrencesofstring unnecessary, doesn't hurt. , might use native base64 methods (nsdata methods base64encodeddatawithoptions or base64encodedstringwithoptions in ios 7, base64encoding in ios versions prior 7) rather afnetworking's, don't think problem either.
assuming userid , password correct , server using basic authentication (which assume correct if curl succeeding), thing incorrect here call sethttpbody get request. nsurlconnection not send body get request (nor should it, body semantically meaningless in get requests). if want send request body, should use post. or if want send parameters in get request, can add them url, not body.
Comments
Post a Comment