通过POST方法发送Json请求[关闭]

Posted

技术标签:

【中文标题】通过POST方法发送Json请求[关闭]【英文标题】:Send Json Request By POST method [closed] 【发布时间】:2014-11-10 09:10:27 【问题描述】:

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

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

这是我的链接http:abcd/api

内容类型 - 应用程序/json

我的职责是什么?我将如何进行。

【问题讨论】:

你必须发布给定的 JSON 或者它是你将得到的响应? 这正在被投票?干什么用的? 给出完整的 url ,http:rdplive.biz/api -- 不行 @ZeMoon - 为什么你对此投赞成票? ,就这么简单? 这是一个更常见的问题:“如何向服务器发送数据并获得响应”。 :// 【参考方案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.

【讨论】:

【参考方案2】:

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

【讨论】:

【参考方案3】:

示例编码

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


 

【讨论】:

【参考方案4】:

表格视图.h

   #import <UIKit/UIKit.h>

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

 @end

表格视图.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

【讨论】:

以上是关于通过POST方法发送Json请求[关闭]的主要内容,如果未能解决你的问题,请参考以下文章

如何通过远程方法发送 json-rpc http post 请求并在 java 中传递加密参数

PHP如何通过Post请求发送Json数据

NEST/Elasticsearch.Net 发送原始JSON请求(Post数据)

如何发送带有 URL 参数和 JSON 正文的 POST? [关闭]

如何通过 HttpClient 在 POST 请求中将 JSON 数据作为正文发送

使用 Alamofire 请求方法在 POST 的请求正文中发送 JSON 对象数组