通过POST方法发送Json请求

时间:2014-11-10 09:10:28

标签: ios objective-c json parsing

我是IOS的新手; 我必须将以下JSON发布到给定链接的服务器,之后我将得到响应。

{"req" : {"apikey" : "apikey","service" : "getcat","id" : "MOMTest00011","ptransid" : "","params" : [ {"k" : "mboxid","v" :"f7"}, {"k" : "version","v" :"0"} ]}}

这是我的链接http:abcd/api

内容类型 - application / json

我的功能是什么?我将如何进行。

4 个答案:

答案 0 :(得分:1)

以下是如何使用JSON数据为POST设置NSURLRequest。

NSDictionary *dicJSON; //Represents your JSON in dictionary format.
NSError *error;

NSData *data = [NSJSONSerialization dataWithJSONObject:dicJSON options:0 error:&error];

if (error)
{
    //Data was not encoded successfully.
    NSLog(@"%@", [error localizedDescription]);
}
else
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"your url here"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSString *postLength=[NSString stringWithFormat:@"%d", [data length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    [request setHTTPBody:data];

    //Send this request using a NSURLConnection method here.
}

答案 1 :(得分:0)

Json postMethod (单身和标题)

<强>

//http://smartproduct.n-school.com/
#define k_HOSPLIST @"http://"
#define k_HOSPDetails @"http://"

#endif /* Header_h */

.h文件

typedef void(^completionBlock)(NSDictionary *resultDictionary,NSError   
*error);
@interface .hfile : NSObject
+ (void)sendGetMethod:(NSString *)url key:(NSString *)key  
withCompletionHandler:(completionBlock)handler;
+ (void)downloadDataFromServer:(NSString *)baseURL bodyData:
(NSDictionary *)body method:(NSString *)methodName postString:
(NSString*)string withCompletionHandler:(completionBlock)handler;  

.m文件

+ (void)sendGetMethod:(NSString *)url key:(NSString *)key   
withCompletionHandler:(completionBlock)handler {
NSLog(@"url %@",url);
NSLog(@"-------> key %@",key);

 NSString* encodedUrl = [url   
 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL    
 URLWithString:encodedUrl]];

 NSURLSessionTask *getMethodtask = [[NSURLSession sharedSession] 
 dataTaskWithRequest:request completionHandler:^(NSData * _Nullable   
 data, 
 NSURLResponse * _Nullable response, NSError * _Nullable error) {

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"sendGetMethod - sendAsynchronousRequest - Completion   
     Block");
        if (error)
        {
            //[k_AppDelegate   
        showAlertwithTitle:LocalizedString(@"Sorry!")    
        message:error.localizedDescription    
        buttonTitle1:LocalizedString(@"OK") 
        buttonTitle2:@""];
        }
        else if (data == nil)
        {

      // [k_AppDelegate showAlertwithTitle:LocalizedString(@"Error!")        
      message:LocalizedString(@"The specified server could not be  
      found.") 
      buttonTitle1:LocalizedString(@"OK") buttonTitle2:@""];
        }
        else
        {
        NSDictionary *encodeDictionary = [NSJSONSerialization    
        JSONObjectWithData:data options:NSJSONReadingMutableLeaves  
        error:nil];

        if (![encodeDictionary isEqual:[NSNull null]] &&    
         encodeDictionary != nil)
            {
                if(handler)
                {
                    handler(encodeDictionary, nil);
                }
        else if([[encodeDictionary objectForKey:@"status"]       

                {
                    //[k_AppDelegate       
           showAlertwithTitle:LocalizedString(@"AlertTitle") message:
            [encodeDictionary objectForKey:@"message"]  
           buttonTitle1:LocalizedString(@"OK") buttonTitle2:@""];
                }
            }
            else
            {
                //[k_AppDelegate   
          showAlertwithTitle:LocalizedString(@"Error!")  
 message:LocalizedString(@"The specified server could not be found.")   
   buttonTitle1:LocalizedString(@"OK") buttonTitle2:@""];
            }
        }
    });
}];
[getMethodtask resume];
}

+ (void)downloadDataFromServer:(NSString *)baseURL bodyData: 
(NSDictionary *)body method:(NSString *)methodName postString:
 (NSString*)string withCompletionHandler:(completionBlock)handler;
{
NSString *getFullServer = [NSString stringWithFormat:@"%@",baseURL];
//Pass the parameters and Set the URL
NSURL *urlString = [NSURL URLWithString:getFullServer];
NSString *post = [NSString stringWithFormat:@"%@",string];
// Convert NSString to NSData format
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding                        
allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned   
 long)[postData length]];
// Create the URL Request and set the neccesary parameters
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:urlString];
[request setHTTPMethod:methodName];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded"   
forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSURLSessionTask *downloadTask = [[NSURLSession sharedSession]  
dataTaskWithRequest:request completionHandler:^(NSData * _Nullable   
data,  
NSURLResponse * _Nullable response, NSError * _Nullable error) {

    dispatch_async(dispatch_get_main_queue(), ^{

        //[(AppDelegate *)[[UIApplication   
       sharedApplication]delegate]stopIndicator];

        if (error)
        {
            //[k_AppDelegate    
       showAlertwithTitle:LocalizedString(@"Sorry!") 
  message:error.localizedDescription    
  buttonTitle1:LocalizedString(@"OK") buttonTitle2:@""];

        } else if (data == nil)
        {
        // [k_AppDelegate   
        showAlertwithTitle:LocalizedString(@"Error!") 
      message:LocalizedString(@"The specified server could not be 
      found.") buttonTitle1:LocalizedString(@"OK") buttonTitle2:@""];

        } else {

            NSDictionary *encodeDictionary = [NSJSONSerialization   
       JSONObjectWithData:data options:NSJSONReadingMutableLeaves  

            if (![encodeDictionary isEqual:[NSNull null]] && 
     encodeDictionary != nil) {


                if(handler)
                {
                    handler(encodeDictionary, nil);
                }
                else if ([[encodeDictionary objectForKey:@"status"]  
          integerValue] != 1)
                {
               // [k_AppDelegate 
         showAlertwithTitle:LocalizedString(@"AlertTitle") message:
      [encodeDictionary objectForKey:@"message"]  
   buttonTitle1:LocalizedString(@"OK") buttonTitle2:@""];
                }
            }
            else
            {
                //[k_AppDelegate  
       showAlertwithTitle:LocalizedString(@"Error!")  
 message:LocalizedString(@"The specified server could not be found.")  
      buttonTitle1:LocalizedString(@"OK") buttonTitle2:@""]; 
            }

        }
    });
}];
[downloadTask resume];
}

答案 2 :(得分:0)

样本编码

·H

 #import <UIKit/UIKit.h>
  #import "Header.h"
  @interface ViewController :      
 UIViewController<UITableViewDelegate,UITableViewDataSource>
 @property (weak, nonatomic) IBOutlet UITableView *tableView;

 @end

的.m

  #import "ViewController.h"
  #import "StringPOSTMethod.h"
  #import "TableViewCell.h"
  #import "HospitalViewController.h"

{
NSMutableArray *array;
NSInteger selectindex;
}
@end

@implementation ViewController


 - (void)viewDidLoad {
 [super viewDidLoad];




[StringPOSTMethod downloadDataFromServer:k_CITYLIST bodyData:nil method:@"POST" postString:[NSString stringWithFormat:@"CITY_ID=1&CITY_ID=2"] withCompletionHandler:^(NSDictionary *resultDictionary, NSError *error)
      {
    NSLog(@"success is %@", resultDictionary);

          array = [[NSMutableArray alloc]init];
          array = [[resultDictionary objectForKey:@"details"] mutableCopy];
    [_tableView reloadData];
}];




}



-(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 =@"tablecell";

TableViewCell * cell = [tableView 
dequeueReusableCellWithIdentifier:cellid];

cell. cityName.text =[[array    
valueForKey:@"city_name"]objectAtIndex:indexPath.row];

return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
{
selectindex=indexPath.row;
[self performSegueWithIdentifier:@"hospitalView" sender:self];

}



#pragma mark - Navigation


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:@"hospitalView"])
{
    hospitalViewController *obj =segue.destinationViewController;
    obj.cityname =[[array   
     valueForKey:@"city_name"]objectAtIndex:selectindex];
    obj.cityId =[[array 
    valueForKey:@"city_id"]objectAtIndex:selectindex];
  }


 }

答案 3 :(得分:0)

table view.h

   #import <UIKit/UIKit.h>

  @interface TableViewCell : UITableViewCell
  @property (weak, nonatomic) IBOutlet UILabel *displyLbl;

 @end

table view.m

 @implementation TableViewCell

- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
 }

 - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];

// Configure the view for the selected state
}

 @end

hosdet.h

#import <UIKit/UIKit.h>
#import "Header.h"
 @interface HospitalDetailViewController : 
 UIViewController<UITextViewDelegate>
 @property (strong, nonatomic) IBOutlet UITextView *textview;
 @property (strong,nonatomic)NSString *hospitaldetailid1;
 @property (strong,nonatomic)NSString *cityiddetail1;
 @end

hpde.m

   #import "HospitalDetailViewController.h"
   #import "StringPOSTMethod.h"
   @interface HospitalDetailViewController ()
   {
   NSMutableArray *array;
  }

   @end

  @implementation HospitalDetailViewController

 - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.



 [StringPOSTMethod downloadDataFromServer:k_HOSPITALDETAIL bodyData:nil 
 method:@"POST" postString:[NSString 
 stringWithFormat:@"CITY_ID=%@&HOSPITAL_ID=%@",
 _cityiddetail1,_hospitaldetailid1] withCompletionHandler
  :^(NSDictionary *resultDictionary, NSError *error)
 {
     NSLog(@"success is %@", resultDictionary);

     array = [[NSMutableArray alloc]init];
     array =[[resultDictionary objectForKey:@"details"]mutableCopy];
     _textview.text = [NSString stringWithFormat:@"%@",
  [array valueForKey:@"detail"]];
 }];


 }

 - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
  }

 /*
 #pragma mark - Navigation

// In a storyboard-based application, you will often want to do a 
 little      preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/

@end

hoaviewc.h

#import <UIKit/UIKit.h>
#import "Header.h"

 @interface HospitalViewController : 
 UIViewController<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *hospitalTable;
 @property (strong,nonatomic)NSString *recivecity;
 @property (strong,nonatomic)NSString *cityid;
 @end

hosviec.m

 #import "HospitalViewController.h"

 #import "StringPOSTMethod.h"
 #import "hospitalTableViewCell.h"
 #import "depatmentViewController.h"


 @interface HospitalViewController ()
 {
NSMutableArray *hospitalarray;
NSInteger selecthospitalid;

}

@end

 @implementation HospitalViewController

 - (void)viewDidLoad {
 [super viewDidLoad];


 self.title = self.recivecity;



    [StringPOSTMethod downloadDataFromServer:k_HOSPITALLIST bodyData:nil 
  method:@"POST" postString:
  [NSString stringWithFormat:@"CITY_ID=%@",_cityid] 
  withCompletionHandler:^(NSDictionary *resultDictionary, NSError *error)
     {
         NSLog(@"success is %@", resultDictionary);

         hospitalarray = [[NSMutableArray alloc]init];
     hospitalarray =[[resultDictionary objectForKey:@"details"]mutableCopy];
          [_hospitalTable reloadData];

     }];


 }



 #pragma mark- UITABLE View Delegate
 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
 return 1;
 }
 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(   
 NSInteger)section
 {
 return hospitalarray.count;
 }
-(UITableViewCell *)tableView:(UITableView *)tableView 
cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
  static NSString *cellid = @"hospitalcell";
     hospitalTableViewCell *cell = [tableView 
  dequeueReusableCellWithIdentifier:cellid];


    cell.hopitalList.text = [[hospitalarray 
   valueForKey:@"name"]objectAtIndex:indexPath.row];


  return cell;
  }

  -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
  (NSIndexPath *)indexPath
 {

  selecthospitalid=indexPath.row;
   [self performSegueWithIdentifier:@"depatment" sender:self];
  }





 - (void)didReceiveMemoryWarning {
 [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
  }

pragma mark - 导航

   // In a storyboard-based application, you will often want to do a little 
  - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

  if ([segue.identifier isEqualToString:@"depatment"]) {
    depatmentViewController *obj = segue.destinationViewController;
    obj.hospitalid = [[hospitalarray 
    valueForKey:@"hospital_id"]objectAtIndex:selecthospitalid];
    obj.cityiddepartment = [NSString stringWithFormat:@"%@",_cityid];
 }
 //     Get the new view controller using [segue destinationViewController].
 //     Pass the selected object to the new view controller.
 }


@end

docviec.h

 #import <UIKit/UIKit.h>
 #include "Header.h"

 @interface DoctorsViewController :    
 UIViewController<UITableViewDelegate,UITableViewDataSource>
 @property (strong, nonatomic) IBOutlet UITableView *doctorTable;
 @property(strong,nonatomic)NSString *hospitaliddoctor;
 @property(strong,nonatomic)NSString *deptiddoctor;

 @end

doctviec.m

 #import "DoctorsViewController.h"
  #import "StringPOSTMethod.h"

 @interface DoctorsViewController ()
 {
NSMutableArray *doctorarray;
}

@end

  @implementation DoctorsViewController

 - (void)viewDidLoad {
 [super viewDidLoad];
// Do any additional setup after loading the view.
[StringPOSTMethod downloadDataFromServer:k_DOCTORSLIST bodyData:nil 
method:@"POST" postString:
[NSString stringWithFormat:@"HOSPITAL_ID=%@&DEPARTMENT_ID=%@",
self.hospitaliddoctor,self.deptiddoctor] 
withCompletionHandler:^(NSDictionary *resultDictionary, NSError *error)
 {
     NSLog(@"success is %@", resultDictionary);

     doctorarray = [[NSMutableArray alloc]init];
     doctorarray =[[resultDictionary objectForKey:@"details"]mutableCopy];
     [_doctorTable reloadData];

 }];


 }




 - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
 }

 #pragma mark- UITableview
 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
 return 1;
}

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:  
 (NSInteger)section
 {
return doctorarray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView 
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellid = @"doctr";

UITableViewCell *cell = [tableView 
dequeueReusableCellWithIdentifier:cellid];

cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault 
reuseIdentifier:cellid];

cell.textLabel.text = [[doctorarray    
valueForKey:@"spacialist_name"]objectAtIndex:indexPath.row];

return cell;
}

depviec.h

 #import <UIKit/UIKit.h>
 #import "Header.h"

 @interface depatmentViewController :   
 UIViewController<UITableViewDelegate,UITableViewDataSource>
 @property (strong, nonatomic) IBOutlet UITableView *tableviewDepatment;
 @property (strong,nonatomic)NSString *hospitalid;
 @property (strong,nonatomic)NSString *cityiddepartment;
 - (IBAction)DetailsBton:(id)sender;
 @end

depvi.m

 #import "depatmentViewController.h"
  #import "StringPOSTMethod.h"
  #import "HospitalDetailViewController.h"
   #import "DoctorsViewController.h"
  @interface depatmentViewController ()
  {
 NSMutableArray *array;
 NSInteger doctorselct;
  }

 @end

 @implementation depatmentViewController

 - (void)viewDidLoad {
 [super viewDidLoad];
// Do any additional setup after loading the view.

 [StringPOSTMethod downloadDataFromServer:k_DEPARTMENTLIST bodyData:nil 
 method:@"POST" postString:
 [NSString stringWithFormat:@"CITY_ID=%@&HOSPITAL_ID=%@",
 self.cityiddepartment,self.hospitalid] withCompletionHandler:^(NSDictionary 
  *resultDictionary, NSError *error)
 {
     NSLog(@"success is %@", resultDictionary);

     array = [[NSMutableArray alloc]init];

     array =[[resultDictionary objectForKey:@"details"]mutableCopy];

     NSLog(@"%@",array);
     [_tableviewDepatment reloadData];

   }];
  }



  - (void)didReceiveMemoryWarning {
 [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
 }

 #pragma mark-UITable Delegate

 -(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=@"depatmentid";

 UITableViewCell *cell = [tableView    
 dequeueReusableCellWithIdentifier:cellid];


 cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault 
  reuseIdentifier:cellid];


 cell.textLabel.text = [[array 
  valueForKey:@"dept_name"]objectAtIndex:indexPath.row];


return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

doctorselct = indexPath.row;
[self performSegueWithIdentifier:@"doctor" sender:self];

}

   #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little 
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

  if ([segue.identifier isEqualToString:@"detailll"])
{
    HospitalDetailViewController *obj = segue.destinationViewController;
    obj.hospitaldetailid1 = self.hospitalid;
    obj.cityiddetail1 = self.cityiddepartment;
}

else
{
    DoctorsViewController *obj1 = segue.destinationViewController;
    obj1.hospitaliddoctor = self.hospitalid;
    obj1.deptiddoctor = [[array 
    valueForKey:@"dept_id"]objectAtIndex:doctorselct];
 }
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}


  - (IBAction)DetailsBton:(id)sender {
   [self performSegueWithIdentifier:@"detailll" sender:self];
  }


 @end