program story

POST NSURLRequest에 데이터 추가

inputbox 2020. 9. 23. 07:35
반응형

POST NSURLRequest에 데이터 추가


기존에 데이터를 어떻게 추가 POST NSURLRequest합니까? 새 매개 변수를 추가해야합니다 userId=2323.


타사 클래스를 사용하지 않으려면 다음은 게시물 본문을 설정하는 방법입니다.

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];

[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                             delegate:self];

키 / 값 쌍을 게시물 문자열에 추가하기 만하면됩니다.


에 대한 모든 변경은 NSMutableURLRequest호출하기 전에 이루어져야합니다 NSURLConnection.

위의 코드를 복사하여 붙여 넣은 다음 실행 TCPMon하고 요청이 GET예상 된 대신에 나타나는 것을 보면이 문제가 발생 합니다 POST.

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                     cachePolicy:NSURLRequestUseProtocolCachePolicy
                                 timeoutInterval:60.0];


[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                         delegate:self];

POST요청 형성에 대한 이전 게시물 은 대체로 정확합니다 (URL이 아닌 본문에 매개 변수 추가). 그러나 예약 된 문자 (예 : 공백, 앰퍼샌드, 더하기 기호)가 포함 된 입력 데이터의 가능성이있는 경우 이러한 예약 된 문자를 처리해야합니다. 즉, 입력을 퍼센트 이스케이프해야합니다.

//create body of the request

NSString *userid = ...
NSString *encodedUserid = [self percentEscapeString:userid];
NSString *postString    = [NSString stringWithFormat:@"userid=%@", encodedUserid];
NSData   *postBody      = [postString dataUsingEncoding:NSUTF8StringEncoding];

//initialize a request from url

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:postBody];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

//initialize a connection from request, any way you want to, e.g.

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

어디 precentEscapeString메서드는 다음과 같이 정의된다 :

- (NSString *)percentEscapeString:(NSString *)string
{
    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef)string,
                                                                                 (CFStringRef)@" ",
                                                                                 (CFStringRef)@":/?@!$&'()*+,;=",
                                                                                 kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}

유망한 NSString방법 stringByAddingPercentEscapesUsingEncoding(현재는 더 이상 사용되지 않음)이 있는데, 매우 유사한 작업을 수행하지만 사용하려는 유혹에 저항합니다. 일부 문자 (예 : 공백 문자)를 처리하지만 다른 일부 (예 : +또는 &문자) 는 처리하지 않습니다 .

The contemporary equivalent is stringByAddingPercentEncodingWithAllowedCharacters, but, again, don't be tempted to use URLQueryAllowedCharacterSet, as that also allows + and & pass unescaped. Those two characters are permitted within the broader "query", but if those characters appear within a value within a query, they must escaped. Technically, you can either use URLQueryAllowedCharacterSet to build a mutable character set and remove a few of the characters that they've included in there, or build your own character set from scratch.

For example, if you look at Alamofire's parameter encoding, they take URLQueryAllowedCharacterSet and then remove generalDelimitersToEncode (which includes the characters #, [, ], and @, but because of a historical bug in some old web servers, neither ? nor /) and subDelimitersToEncode (i.e. !, $, &, ', (, ), *, +, ,, ;, and =). This is correct implementation (though you could debate the removal of ? and /), though pretty convoluted. Perhaps CFURLCreateStringByAddingPercentEscapes is more direct/efficient.


 NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                    timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
 NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

The example code above was really helpful to me, however (as has been hinted at above), I think you need to use NSMutableURLRequest rather than NSURLRequest. In its current form, I couldn't get it to respond to the setHTTPMethod call. Changing the type fixed things right up.


Any one looking for a swift solution

let url = NSURL(string: "http://www.apple.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPBody = "company=Locassa&quality=AWESOME!".dataUsingEncoding(NSUTF8StringEncoding)

참고URL : https://stackoverflow.com/questions/6148900/append-data-to-a-post-nsurlrequest

반응형