จะส่งคำขอ POST และ GET ได้อย่างไร

ฉันต้องการส่ง JSON ของฉันไปที่ URL (POST และ GET)

NSMutableDictionary *JSONDict = [[NSMutableDictionary alloc] init];
[JSONDict setValue:"myValue" forKey:"myKey"];

NSData *JSONData = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:nil];

รหัสคำขอปัจจุบันของฉันใช้งานไม่ได้

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

การใช้ ASIHTTPRequest ไม่ เป็นคำตอบที่น่าเชื่อถือ


person Aleksander Azizi    schedule 06.10.2011    source แหล่งที่มา


คำตอบ (3)


การส่งคำขอ POST และ GET ใน iOS นั้นค่อนข้างง่าย และไม่จำเป็นต้องมีกรอบงานเพิ่มเติม


POST คำขอ:

เราเริ่มต้นด้วยการสร้าง POST's body (เช่น สิ่งที่เราต้องการส่ง) ของเราเป็น NSString และแปลงเป็น NSData

objective-c

NSString *post = [NSString stringWithFormat:@"test=Message&this=isNotReal"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

ต่อไป เราจะอ่าน postData's length เพื่อที่เราจะได้ส่งต่อในคำขอได้

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

ตอนนี้เรามีสิ่งที่ต้องการโพสต์แล้ว เราสามารถสร้าง NSMutableURLRequest และรวม postData ของเราได้

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

swift

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;

และสุดท้าย เราสามารถส่งคำขอของเรา และอ่านคำตอบโดยสร้าง NSURLSession ใหม่:

objective-c

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

swift

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 คำขอ:

ด้วยคำขอ GET โดยพื้นฐานแล้วจะเป็นสิ่งเดียวกัน เพียง ไม่มี HTTPBody และ Content-Length

objective-c

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

swift

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

หมายเหตุด้านข้าง คุณสามารถเพิ่ม Content-Type (และข้อมูลอื่นๆ) ได้โดยการเพิ่มสิ่งต่อไปนี้ใน NSMutableURLRequest ของเรา เซิร์ฟเวอร์อาจจำเป็นต้องใช้สิ่งนี้เมื่อทำการร้องขอ เช่น

objective-c

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

รหัสตอบกลับสามารถอ่านได้โดยใช้ [(NSHTTPURLResponse*)response statusCode]

swift

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

อัปเดต: sendSynchronousRequest เลิกใช้แล้ว จาก ios9 และ osx-elcapitan (10.11) และออก <ส>

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

person Aleksander Azizi    schedule 17.07.2012
comment
อธิบายได้ดีมาก ขอบคุณ. :) - person Baby Groot; 26.03.2013
comment
ทำความสะอาด. +1. @อเล็กซานเดอร์ อาซิซี - person Chisx; 25.01.2014
comment
ในกรณีของฉัน ฉันต้องใช้ GET และส่งข้อมูล json ด้วย ฉันสามารถเพิ่ม HTTPBody ได้หรือไม่ - person Satyam; 26.03.2014
comment
ฉันได้รับคำขอตอบกลับเป็นโมฆะ จะเป็นประเด็นอะไร? - person niravpatel; 04.12.2014
comment
เป็นไปได้มากว่าเป็นคำขอที่ไม่ถูกต้องหรือข้อมูลฝั่งเซิร์ฟเวอร์ล้มเหลว - person Aleksander Azizi; 04.12.2014
comment
สวัสดี เราจะส่งพารามิเตอร์อินพุตโดยใช้โค้ดด้านบนได้อย่างไร กรุณาแจ้งให้เราทราบ. - person Narasimha Nallamsetty; 14.04.2015
comment
สวัสดี @AleksanderAzizi คำตอบที่ยอดเยี่ยม ฉันสงสัยว่าคุณจะแทรกข้อมูลลงในฟิลด์ใดฟิลด์หนึ่งในวัตถุ JSON ได้อย่างไร เช่น อยากได้ object ชื่อ Player และ field ชื่อ Name และอยากอัพเดทเฉพาะชื่อ จะต้องทำอย่างไร? - person App Dev Guy; 16.04.2015
comment
@Satyam ด้วยคำขอ GET คุณจะรวมข้อมูลไว้ในส่วนหัวและ/หรือ url คำขอ GET ไม่มีเนื้อหา - person Aleksander Azizi; 28.04.2016
comment
ขอบคุณมันได้ผลฉัน - person ssowri1; 28.03.2017
comment
ขอบคุณมาก หลังจากลองมาหลายวิธีแล้ว ฉันก็จบงานด้วยวิธีแก้ปัญหาของคุณ :-) - person Daya Kevin; 13.10.2017
comment
คุณช่วยอธิบายรหัสการใช้ NSURLConnection แทน URLSession ได้อย่างรวดเร็วได้ไหม - person Rashid KC; 27.03.2018
comment
ฟังก์ชันของ @KayCee NSURLConnection สำหรับการโหลดข้อมูลแบบอะซิงโครนัสเลิกใช้แล้ว ดูเอกสารประกอบของ Apple เกี่ยวกับ NSURLConnection - person Aleksander Azizi; 29.03.2018

เมื่อใช้ RestKit คุณสามารถส่งคำขอ POST ง่ายๆ ได้ (ดู GitHub สำหรับรายละเอียดเพิ่มเติม)

นำเข้า RestKit ในไฟล์ส่วนหัวของคุณ

#import <RestKit/RestKit.h>

จากนั้นคุณสามารถเริ่มต้นด้วยการสร้าง RKRequest ใหม่

RKRequest *MyRequest = [[RKRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"http://myurl.com/FakeUrl/"]];

จากนั้นระบุประเภทของคำขอที่คุณต้องการ (ในกรณีนี้คือคำขอ POST)

MyRequest.method = RKRequestMethodPOST;
MyRequest.HTTPBodyString = YourPostString;

จากนั้นตั้งค่าคำขอของคุณเป็น JSON ใน additionalHTTPHeaders

MyRequest.additionalHTTPHeaders = [[NSDictionary alloc] initWithObjectsAndKeys:@"application/json", @"Content-Type", @"application/json", @"Accept", nil];

ในที่สุดคุณสามารถส่งคำขอได้

[MyRequest send];

นอกจากนี้ คุณยังสามารถ NSLog คำขอของคุณเพื่อดูผลลัพธ์ได้

RKResponse *Response = [MyRequest sendSynchronously];
NSLog(@"%@", Response.bodyAsString);

แหล่งที่มา: RestKit.org และ ฉัน.

person Aleksander Azizi    schedule 12.06.2012

การควบคุมมุมมอง.h

@interface ViewController     UIViewController<UITableViewDataSource,UITableViewDelegate>

  @property (weak, nonatomic) IBOutlet UITableView *tableView;
  @property (strong,nonatomic)NSArray *array;
  @property NSInteger select;
  @end

วิว.ม

  - (void)viewDidLoad {
 [super viewDidLoad];
 NSString *urlString = [NSString stringWithFormat:    @"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=11.021459,76.916332&radius=2000&types=atm&sensor=false&key=AIzaS yD7c1IID7zDCdcfpC69fC7CUqLjz50mcls"];
 NSURL *url = [NSURL URLWithString: urlString];
 NSData *data = [NSData dataWithContentsOfURL:url];
 NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:      
 data options: 0 error: nil];
 _array = [[NSMutableArray alloc]init];
 _array = [[jsonData objectForKey:@"results"] mutableCopy];
[_tableView reloadData];}
// Do any additional setup after loading the view, typically from a         



 - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
  }
 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

return 1;
  }

  - (NSInteger)tableView:(UITableView *)tableView
  numberOfRowsInSection:(NSInteger)section {

 return _array.count;
  }

 - (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 static NSString *cellid = @"cell";
 UITableViewCell *cell = [tableView
                         dequeueReusableCellWithIdentifier:cellid];
 cell = [[UITableViewCell
         alloc]initWithStyle:UITableViewCellStyleSubtitle
        reuseIdentifier:cellid];

 cell.textLabel.text = [[_array
 valueForKeyPath:@"name"]objectAtIndex:indexPath.row]; 
 cell.detailTextLabel.text = [[_array 
 valueForKeyPath:@"vicinity"]objectAtIndex:indexPath.row];
 NSURL *imgUrl = [NSURL URLWithString:[[_array
 valueForKey:@"icon"]objectAtIndex:indexPath.row]];  
 NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
 cell.imageView.layer.cornerRadius =        
 cell.imageView.frame.size.width/2;
 cell.imageView.layer.masksToBounds = YES;
 cell.imageView.image = [UIImage imageWithData:imgData];

 return cell;
 }

 @end

ตารางเซลล์.h

 @interface TableViewCell : UITableViewCell
 @property (weak, nonatomic) IBOutlet UIImageView *imgView;
 @property (weak, nonatomic) IBOutlet UILabel *lblName;
 @property (weak, nonatomic) IBOutlet UILabel *lblAddress;
person sasidharan.M    schedule 08.05.2017
comment
การเข้ารหัสข้างต้นใช้สำหรับวิธีการรับ - person sasidharan.M; 08.05.2017