Ich möchte mein JSON
an eine URL senden (POST
und GET
).
NSMutableDictionary *JSONDict = [[NSMutableDictionary alloc] init];
[JSONDict setValue:"myValue" forKey:"myKey"];
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:nil];
Mein aktueller Anforderungscode funktioniert nicht.
NSMutableURLRequest *requestData = [[NSMutableURLRequest alloc] init];
[requestData setURL:[NSURL URLWithString:@"http://fake.url/"];];
[requestData setHTTPMethod:@"POST"];
[requestData setValue:postLength forHTTPHeaderField:@"Content-Length"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[requestData setHTTPBody:postData];
Die Verwendung von ASIHTTPRequest
ist nicht eine verlässliche Antwort.
Das Senden von POST
und GET
Anfragen unter iOS ist ganz einfach. und es besteht keine Notwendigkeit für ein zusätzliches Framework.
POST
Anfrage:Wir beginnen, indem wir die POST
's body
(also das, was wir senden möchten) als NSString
erstellen und in NSData
konvertieren.
NSString *post = [NSString stringWithFormat:@"test=Message&this=isNotReal"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
Als nächstes lesen wir das postData
des length
, damit wir es in der Anfrage weitergeben können.
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
Nachdem wir das haben, was wir veröffentlichen möchten, können wir ein NSMutableURLRequest
erstellen und unser postData
einbinden.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://YourURL.com/FakeURL"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
let post = "test=Message&this=isNotReal"
let postData = post.data(using: String.Encoding.ascii, allowLossyConversion: true)
let postLength = String(postData!.count)
var request = URLRequest(url: URL(string: "http://YourURL.com/FakeURL/PARAMETERS")!)
request.httpMethod = "POST"
request.addValue(postLength, forHTTPHeaderField: "Content-Length")
request.httpBody = postData;
Und schließlich können wir unsere Anfrage senden und die Antwort lesen, indem wir ein neues NSURLSession
erstellen:
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"Request reply: %@", requestReply);
}] resume];
let session = URLSession(configuration: .default)
session.dataTask(with: request) {data, response, error in
let requestReply = NSString(data: data!, encoding: String.Encoding.ascii.rawValue)
print("Request reply: \(requestReply!)")
}.resume()
GET
Anfrage:Mit der GET
-Anforderung ist es im Grunde dasselbe, nur ohne die HTTPBody
und Content-Length
.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://YourURL.com/FakeURL/PARAMETERS"]];
[request setHTTPMethod:@"GET"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"Request reply: %@", requestReply);
}] resume];
var request = URLRequest(url: URL(string: "http://YourURL.com/FakeURL/PARAMETERS")!)
request.httpMethod = "GET"
let session = URLSession(configuration: .default)
session.dataTask(with: request) {data, response, error in
let requestReply = NSString(data: data!, encoding: String.Encoding.ascii.rawValue)
print("Request reply: \(requestReply!)")
}.resume()
Als Randnotiz können Sie Content-Type
(Und andere Daten) hinzufügen, indem Sie das Folgende zu unserem NSMutableURLRequest
hinzufügen. Dies kann vom Server erforderlich sein, wenn beispielsweise ein json angefordert wird.
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
Der Antwortcode kann auch mit [(NSHTTPURLResponse*)response statusCode]
gelesen werden.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
Update: sendSynchronousRequest
ist veraltet von ios9 und osx-elcapitan (10.11) und aus.
NSURLResponse *requestResponse; NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil]; NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding]; NSLog(@"requestReply: %@", requestReply);
Mit RestKit können Sie eine einfache POST) Anfrage stellen (siehe diese GitHub Seite für weitere Details).
Importieren Sie RestKit in Ihre Header-Datei.
#import <RestKit/RestKit.h>
Anschließend können Sie ein neues RKRequest
erstellen.
RKRequest *MyRequest = [[RKRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"http://myurl.com/FakeUrl/"]];
Geben Sie dann an, welche Art von Anforderung Sie stellen möchten (in diesem Fall eine POST
-Anforderung).
MyRequest.method = RKRequestMethodPOST;
MyRequest.HTTPBodyString = YourPostString;
Stellen Sie dann Ihre Anfrage als JSON in additionalHTTPHeaders
ein.
MyRequest.additionalHTTPHeaders = [[NSDictionary alloc] initWithObjectsAndKeys:@"application/json", @"Content-Type", @"application/json", @"Accept", nil];
Schließlich können Sie die Anfrage senden.
[MyRequest send];
Zusätzlich können Sie NSLog
Ihre Anfrage stellen, um das Ergebnis zu sehen.
RKResponse *Response = [MyRequest sendSynchronously];
NSLog(@"%@", Response.bodyAsString);
Quellen: RestKit.org und Me .
-(void)postmethod
{
NSString * post =[NSString stringWithFormat:@"Email=%@&Password=%@",_txt_uname.text,_txt_pwd.text];
NSData *postdata= [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength=[NSString stringWithFormat:@"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];
NSLog(@"%@",app.mainurl);
// NSString *str=[NSString stringWithFormat:@"%@Auth/Login",app.mainurl];
NSString *str=YOUR URL;
[request setURL:[NSURL URLWithString:str]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postdata];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnstring=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSMutableDictionary *dict=[returnstring JSONValue];
NSLog(@"%@",dict);
}
-(void)GETMethod
{
NSString *appurl;
NSString *temp [email protected]"YOUR URL";
appurl = [NSString stringWithFormat:@"%@uid=%@&cid=%ld",temp,user_id,(long)clubeid];
appurl = [appurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:appurl]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSMutableDictionary *dict_eventalldata=[returnString JSONValue];
NSString *success=[dict_eventalldata objectForKey:@"success"];
}