首頁>Program>source

我想發送我的 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];

使用 ASIHTTPRequestnot 一个可靠的答案。

最新回復
  • 5月前
    1 #

    發送 POSTGET 在iOS中进行請求非常容易; 不需要其他框架。


    POST 請求:

    我们首先建立自己的 POSTbody (ergo。我们想要發送的)作為 NSString ,並將其轉換為 NSData

    objective-c

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

    接下来,我们阅讀《 postData》 的 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];
    

    迅速

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

    迅速

    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

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

    迅速

    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 .服務器在請求(例如json)時可能会要求這樣做。

    objective-c

    [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")
    

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

  • 5月前
    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.org和我。

  • 5月前
    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 [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"];
    }
    

  • 5月前
    4 #

    Get Request :

    -(void)fetchData{
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData* data = [NSData dataWithContentsOfURL:[NSURL
                                                          URLWithString:@"yourURL"]];
            NSLog(@"LatestURL:%@",data);
            NSError* error=nil;
            NSDictionary *jsonDict= [NSJSONSerialization JSONObjectWithData:data
                                                                    options:kNilOptions error:&error];
            NSLog(@"JSON = %@", [[NSString alloc] initWithData:data encoding:
                                 NSUTF8StringEncoding]);
            dispatch_async(dispatch_get_main_queue(), ^{
    
        NSDictionary *statuses=[jsonDict objectForKey:@"result"];
        NSLog(@"SomeStatus :%@",statuses);
        if (!statuses)
        {
            NSLog(@"Error in Json :%@",error);
        }
        else
        {
            [self.arrayTimeline removeAllObjects];
            for(NSDictionary *newValu in statuses)
            {
                [self.arrayTimeline addObject:newValu];
                NSString *ProjectName=[newValu objectForKey:@"project_name"];
                NSLog(@"Project Name : %@",ProjectName);
                NSString *Stage=[newValu objectForKey:@"stage_name"];
                NSLog(@"Stage : %@",Stage);
                NSString *CompTime=[newValu objectForKey:@"completion_time"];
                NSLog(@"Completion Time : %@",CompTime);
                NSString *Status=[newValu objectForKey:@"status"];
                NSLog(@"Status : %@",Status);
            }
            [self.projectTimelineTable reloadData];
        });
    } }); }
    

    JSON Response: {"狀態":"成功","名稱":" project1","地址":" badkal mor地铁站","州":" haryana","城市":" faridabad"," start_time":" 1480586013 "," current_stage":"投標接受"," manager":"不可用"," completion_time":" 1480464000"}

    您可以获得名稱,開始時間等键值,並顯示在標簽上

  • 5月前
    5 #

    视圖控制元件。h

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

    view.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;
    

  • asp.net mvc:RequireJS如何与多个頁面和部分视圖一起使用?
  • ios8:Xcode 6 iOS建立可可觸摸框架-體系結構問题