/ / iOS: HTTP POST अनुरोध कैसे करें? - iphone, उद्देश्य- c, ios

iOS: HTTP POST अनुरोध कैसे करें? - आईफोन, उद्देश्य-सी, आईओएस

मैं iOS के विकास के करीब आ रहा हूं और मुझे HTTP POST अनुरोध करने के लिए मेरे पहले एप्लिकेशन में से एक है।

जहां तक ​​मैं समझ सकता हूं, मुझे उस कनेक्शन का प्रबंधन करना चाहिए जो ए के माध्यम से अनुरोध को संभालता है NSURLConnection ऑब्जेक्ट, जो मुझे एक प्रतिनिधि ऑब्जेक्ट रखने के लिए मजबूर करता है, जो बदले में डेटा घटनाओं को संभाल लेगा।

क्या कोई व्यावहारिक उदाहरण के साथ कार्य को स्पष्ट कर सकता है?

मुझे प्रमाणीकरण डेटा (उपयोगकर्ता नाम और पासवर्ड) भेजने और एक सादे पाठ प्रतिक्रिया वापस लेने के लिए एक https समापन बिंदु से संपर्क करना चाहिए।

उत्तर:

जवाब के लिए 167 № 1

आप निम्नानुसार NSURLConnection का उपयोग कर सकते हैं:

  1. अपन सेट करें NSURLRequest: उपयोग requestWithURL:(NSURL *)theURL अनुरोध को प्रारंभ करने के लिए।

    यदि आपको एक POST अनुरोध और / या HTTP हेडर निर्दिष्ट करने की आवश्यकता है, तो उपयोग करें NSMutableURLRequest साथ में

    • (void)setHTTPMethod:(NSString *)method
    • (void)setHTTPBody:(NSData *)data
    • (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field
  2. अपना अनुरोध 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];
}

जवाब के लिए 13 № 2

EDIT: ASIHTTPRequest को डेवलपर ने छोड़ दिया है। यह अभी भी वास्तव में अच्छा IMO है, लेकिन आपको शायद कहीं और देखना चाहिए।

मैं अत्यधिक उपयोग करने की सलाह देता हूं ASIHTTPRequest लाइब्रेरी यदि आप HTTPS को संभाल रहे हैं।Https के बिना भी यह इस तरह से सामान के लिए एक बहुत अच्छा आवरण प्रदान करता है और जब तक यह खुद को सादे http से अधिक कठिन नहीं है, मुझे लगता है कि पुस्तकालय अच्छा है और इसे शुरू करने का एक शानदार तरीका है।

HTTPS जटिलताओं विभिन्न परिदृश्यों में तुच्छ से दूर हैं, और यदि आप सभी विविधताओं को संभालने में मजबूत होना चाहते हैं, तो आप एएसआई पुस्तकालय को एक वास्तविक मदद पाएंगे।


उत्तर के लिए 7 № 3

मुझे लगा कि मैं इस पोस्ट को थोड़ा अपडेट करूंगा और कहूंगा कि iOS समुदाय का एक बहुत कुछ खत्म हो गया है AFNetworking बाद ASIHTTPRequest छोड़ दिया गया था। मैं इसकी पुरजोर सलाह देता हूँ। यह चारों ओर एक महान आवरण है NSURLConnection और अतुल्यकालिक कॉल के लिए अनुमति देता है, और मूल रूप से कुछ भी आप की आवश्यकता हो सकती है।


जवाब के लिए 6 № 4

यहाँ iOS7 + के लिए एक अद्यतन उत्तर दिया गया है। यह NSURLSession, नई हॉटनेस का उपयोग करता है। अस्वीकरण, यह अप्रयुक्त है और एक पाठ क्षेत्र में लिखा गया था:

- (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+ का उपयोग करें। आमतौर पर मैं AFHTTPSessionManager को उपवर्गित करता हूं, लेकिन मैं संक्षिप्त उदाहरण के लिए यह सब एक विधि में डाल रहा हूं।

- (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 प्रतिक्रिया (अक्सर NS सहार या NSArray) से ऑब्जेक्ट होगा।


उत्तर के लिए 1 № 5

नोट: शुद्ध स्विफ्ट 3 (Xcode 8) उदाहरण: कृपया निम्न नमूना कोड देखें। इसका सरल उदाहरण है dataTask के समारोह URLSession.

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()

}

जवाब के लिए 0 № 6

Xcode 8 और स्विफ्ट 3.0

URLSession का उपयोग:

 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()

URLSession प्रतिनिधि कॉल:

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 / DELETE का उपयोग करना:

 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% परिणाम की गारंटी दें


उत्तर के लिए 0 № 7

इस प्रकार POST HTTP अनुरोध NSURLSession का उपयोग कर iOS 8+ के लिए काम करता है:

- (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];

}

आशा है कि यह आपकी निम्नलिखित आवश्यकता को पूरा करेगा।