【问题标题】:How to send POST and GET request?如何发送 POST 和 GET 请求?
【发布时间】:2011-10-06 10:34:54
【问题描述】:

我想将我的JSON 发送到一个 URL(POSTGET)。

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不是可靠的答案。

【问题讨论】:

    标签: objective-c swift post get nsurlsession


    【解决方案1】:

    在 iOS 中发送POSTGET 请求非常简单;并且不需要额外的框架。


    POST请求:

    我们首先创建POSTbody(因此,我们想发送的内容)为NSString,并将其转换为NSData

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

    接下来,我们读取postDatalength,因此我们可以在请求中传递它。

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

    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 来阅读回复:

    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请求:

    GET 请求基本相同,只是没有HTTPBodyContent-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()
    

    附带说明,您可以通过将以下内容添加到我们的NSMutableURLRequest 来添加Content-Type(和其他数据)。这可能是服务器在请求时需要的,例如

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

    也可以使用[(NSHTTPURLResponse*)response statusCode]读取响应代码。

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

    更新:sendSynchronousRequest (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);
    

    【讨论】:

    • 解释得很好。谢谢你。 :)
    • 干净。 +1。 @Aleksander Azizi
    • 就我而言,我必须使用 GET 并发送 json 数据。我可以添加 HTTPBody 吗?
    • 我收到了对 Null 的 requestReply。会有什么问题?
    • 非常感谢,在尝试了这么多方法之后,我以您的解决方案结束了我的任务。 :-)
    【解决方案2】:

    通过使用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;
    

    然后将您的请求设置为 additionalHTTPHeaders 中的 JSON。

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

    最后,你可以发送请求了。

    [MyRequest send];
    

    此外,您可以NSLog您的请求以查看结果。

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

    来源:RestKit.orgMe

    【讨论】:

      【解决方案3】:
       -(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 =@"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"];
      }
      

      【讨论】:

        【解决方案4】:

        查看控件.h

        @interface ViewController     UIViewController<UITableViewDataSource,UITableViewDelegate>
        
          @property (weak, nonatomic) IBOutlet UITableView *tableView;
          @property (strong,nonatomic)NSArray *array;
          @property NSInteger select;
          @end
        

        查看.m

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

        tablecell.h

         @interface TableViewCell : UITableViewCell
         @property (weak, nonatomic) IBOutlet UIImageView *imgView;
         @property (weak, nonatomic) IBOutlet UILabel *lblName;
         @property (weak, nonatomic) IBOutlet UILabel *lblAddress;
        

        【讨论】:

        • 以上代码是get方法
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-13
        • 1970-01-01
        相关资源
        最近更新 更多