itsource

iOS: HTTP POST 요청을 수행하는 방법은 무엇입니까?

mycopycode 2023. 6. 1. 22:42
반응형

iOS: HTTP POST 요청을 수행하는 방법은 무엇입니까?

저는 iOS 개발을 앞두고 있는데 HTTP POST 요청을 수행할 수 있는 첫 번째 애플리케이션 중 하나를 갖고 싶습니다.

제가 이해하는 한, 요청을 처리하는 연결은 다음을 통해 관리해야 합니다.NSURLConnectionobject, 즉 위임 개체를 강제로 가지게 되어 데이터 이벤트를 처리하게 됩니다.

누가 실무적인 예를 들어 그 과제를 명확히 해주실 수 있나요?

인증 데이터(사용자 이름 및 암호)를 보내고 일반 텍스트 응답을 받는 https 끝점에 문의해야 합니다.

다음과 같이 NSURL 연결을 사용할 수 있습니다.

  1. 설정NSURLRequest사용requestWithURL:(NSURL *)theURL요청을 초기화합니다.

    POST 요청 및/또는 HTTP 헤더를 지정해야 하는 경우NSMutableURLRequest와 함께

    • (void)setHTTPMethod:(NSString *)method
    • (void)setHTTPBody:(NSData *)data
    • (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field
  2. 다음을 사용하여 두 가지 방법으로 요청 보내기NSURLConnection:

    • 동기화:(NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error

      이는 다음을 반환합니다.NSData처리할 수 있는 변수입니다.

      중요:UI가 차단되지 않도록 별도의 스레드에서 동기화 요청을 시작해야 합니다.

    • 비동기식:(void)start

NSURLConnection의 대리자가 다음과 같이 연결을 처리하도록 설정하는 것을 잊지 마십시오.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [self.data setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
    [self.data appendData:d];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"")
                                 message:[error localizedDescription]
                                delegate:nil
                       cancelButtonTitle:NSLocalizedString(@"OK", @"") 
                       otherButtonTitles:nil] autorelease] show];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];

    // Do anything you want with it 

    [responseText release];
}

// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    NSString *username = @"username";
    NSString *password = @"password";

    NSURLCredential *credential = [NSURLCredential credentialWithUser:username
                                                             password:password
                                                          persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}

편집: ASIHTTPRequest가 개발자에 의해 포기되었습니다.아직도 정말 좋은 IMO이지만, 지금은 다른 곳을 찾아봐야 할 것입니다.

HTTPS를 취급하는 경우 ASIHTTPRequest 라이브러리를 사용하는 것을 강력히 추천합니다.https가 없어도 이런 것들을 위한 정말 좋은 포장지를 제공하고 평범한 http를 사용하는 것은 어렵지 않지만, 저는 도서관이 좋고 시작하기에 좋은 방법이라고 생각합니다.

HTTPS 합병증은 다양한 시나리오에서 사소한 것과는 거리가 멀고, 모든 변형을 강력하게 처리하고 싶다면 ASI 라이브러리가 진정한 도움이 된다는 것을 알게 될 것입니다.

저는 이 게시물을 조금 업데이트하고 많은 iOS 커뮤니티가 이후 AF네트워킹으로 이동했다고 말하고 싶습니다.ASIHTTPRequest버려졌습니다.강력 추천합니다.그것은 주변에 좋은 포장지입니다.NSURLConnection그리고 비동기식 통화와 기본적으로 필요한 모든 것을 허용합니다.

iOS7+에 대한 업데이트된 답변입니다.새로운 핫도인 NSURL 세션을 사용합니다.고지 사항: 테스트되지 않았으며 텍스트 필드에 작성되었습니다.

- (void)post {
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://example.com/dontposthere"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    // Uncomment the following two lines if you're using JSON like I imagine many people are (the person who is asking specified plain text)
    // [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    // [request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
    [request setHTTPMethod:@"POST"];
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }];
    [postDataTask resume];
}

-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(    NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
    completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}

또는 AFNetworking 2.0+를 사용하는 것이 좋습니다.보통 저는 AFHTTP SessionManager를 하위 클래스로 분류합니다. 하지만 저는 이 모든 것을 간결한 예를 들기 위해 한 가지 방법으로 설명하고 있습니다.

- (void)post {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"https://example.com"]];
    // Many people will probably want [AFJSONRequestSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // Many people will probably want [AFJSONResponseSerializer serializer];
    manager.responseSerializer = [AFHTTPRequestSerializer serializer];
    manager.securityPolicy.allowInvalidCertificates = NO; // Some servers require this to be YES, but default is NO.
    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"username" password:@"password"];
    [[manager POST:@"dontposthere" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"darn it");
    }] resume];
}

JSON 응답 직렬화기를 사용하는 경우, responseObject는 JSON 응답의 객체가 됩니다(종종 NSDictionary 또는 NSArray).

참고: Pure Swift 3(Xcode 8) 예: 다음 샘플 코드를 사용해 보십시오.의 간단한 예입니다.dataTaskURLSession.

func simpleDataRequest() {

        //Get the url from url string
        let url:URL = URL(string: "YOUR URL STRING")!

        //Get the session instance
        let session = URLSession.shared

        //Create Mutable url request
        var request = URLRequest(url: url as URL)

        //Set the http method type
        request.httpMethod = "POST"

        //Set the cache policy
        request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData

        //Post parameter
        let paramString = "key=value"

        //Set the post param as the request body
        request.httpBody = paramString.data(using: String.Encoding.utf8)

        let task = session.dataTask(with: request as URLRequest) {
            (data, response, error) in

            guard let _:Data = data as Data?, let _:URLResponse = response  , error == nil else {

                //Oops! Error occured.
                print("error")
                return
            }

            //Get the raw response string
            let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))

            //Print the response
            print(dataString!)

        }

        //resume the task
        task.resume()

    }

Xcode 8 및 Swift 3.0

URL 세션 사용:

 let url = URL(string:"Download URL")!
 let req = NSMutableURLRequest(url:url)
 let config = URLSessionConfiguration.default
 let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)

 let task : URLSessionDownloadTask = session.downloadTask(with: req as URLRequest)
task.resume()

URL 세션 대표자 호출:

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {

}


func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, 
didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
                   print("downloaded \(100*writ/exp)" as AnyObject)

}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){

}

GET/POST/PUT/DE 차단 사용:

 let request = NSMutableURLRequest(url: URL(string: "Your API URL here" ,param: param))!,
        cachePolicy: .useProtocolCachePolicy,
        timeoutInterval:"Your request timeout time in Seconds")
    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers as? [String : String] 

    let session = URLSession.shared

    let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
        let httpResponse = response as? HTTPURLResponse

        if (error != nil) {
         print(error)
         } else {
         print(httpResponse)
         }

        DispatchQueue.main.async {
           //Update your UI here
        }

    }
    dataTask.resume()

저는 잘 작동하고 있습니다.100% 결과 보장을 받아보세요.

다음은 NSURLSession을 사용하는 iOS 8+에서 POST HTTP 요청이 작동하는 방법입니다.

- (void)call_PostNetworkingAPI:(NSURL *)url withCompletionBlock:(void(^)(id object,NSError *error,NSURLResponse *response))completion
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    config.URLCache = nil;
    config.timeoutIntervalForRequest = 5.0f;
    config.timeoutIntervalForResource =10.0f;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
    NSMutableURLRequest *Req=[NSMutableURLRequest requestWithURL:url];
    [Req setHTTPMethod:@"POST"];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:Req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {

            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            if (dict != nil) {
                completion(dict,error,response);
            }
        }else
        {
            completion(nil,error,response);
        }
    }];
    [task resume];

}

이것이 당신의 다음 요구사항을 만족시키기를 바랍니다.

언급URL : https://stackoverflow.com/questions/5537297/ios-how-to-perform-a-http-post-request

반응형