将HTTPPOST JSON参数发送到PHP页面-iOS



所以我试图通过POST向php服务器发送一个参数,该参数值必须是JSON值。参数的名称必须是"数据">

我的意思是,对于get方法,它将类似于http://url.com/url/something.php?data={"jsonkey1":1,"jsonkey2":[……或类似的东西

这是我现在拥有的代码,但我无法让它工作。我不喜欢使用外部库,而是使用本机方法。

// Writing JSON...
NSNumber *imagesCount = [[NSNumber alloc] initWithInt:0];
NSMutableArray *arrayList = [[NSMutableArray alloc] init]; // That's an empty array
//[arrayList addObject:@"image1.png"]; [arrayList addObject:@"image2.png"];
NSDictionary *dictionaryJSON = [NSDictionary dictionaryWithObjectsAndKeys:imagesCount, @"count",arrayList,@"list", nil];
NSString *param = @"data=";
NSMutableData *dataJSON = [[NSMutableData alloc]init];
[dataJSON appendData:[param dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryJSON options:NSJSONWritingPrettyPrinted error:&error];;
[dataJSON appendData:jsonData];
NSString* jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
NSLog(@"jsonData as string:n%@, %@", jsonString, error);
jsonString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// Request to server
NSString *url =[NSString stringWithFormat:@"http://url.com/ios/api/get_images_cache.php?"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:[NSString stringWithFormat:@"%i", [dataJSON length]] forHTTPHeaderField:@"Content-Length"];

NSString* jsonStringdat = [[NSString alloc] initWithBytes:[dataJSON bytes] length:[dataJSON length] encoding:NSUTF8StringEncoding];
jsonStringdat=[jsonStringdat stringByReplacingOccurrencesOfString:@" " withString:@""];
jsonStringdat=[jsonStringdat stringByReplacingOccurrencesOfString:@"n" withString:@""];
NSLog(@"Final jsonData as string:n%@, %@", jsonStringdat, error);
//[request setValue:jsonStringdat forHTTPHeaderField:@"data"];
//[request setValue:jsonData forKey:@"data"];
[request setHTTPBody: [jsonStringdat dataUsingEncoding:NSUTF8StringEncoding]];

谢谢你的帮助。

编辑:

我终于做到了,问题出在这两条线上:

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

我把它们取下来,终于开始工作了,谢谢!

NSURLConnection* connection = [NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

添加到最后,然后你需要让你的类符合,然后它就可以知道请求何时成功完成,何时因错误等而失败。此外,我在应用程序中构建请求的方式是:

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
[request setTimeoutInterval:10];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

我希望这能有所帮助!

编辑:此外,在发送之前,请将您必须的JSON转换为字符串。我就是这样做的:

NSData *dataFromJSON = [NSJSONSerialization dataWithJSONObject:jsonObjects options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:dataFromJSON encoding:NSUTF8StringEncoding];

您可以在POST请求中使用application/x-www-form-urlencoded,在该请求中您可以发送许多参数(键/值对)。

请注意,参数键和值必须正确编码。特别是,JSON通常包含许多不能按原样用作参数值的字符。

因此,给定一个表示JSON的对象,jsonRep,它是NSArrayNSDictionary对象,您将获得JSON:

NSError* error;
NSData* json = [NSJSONSerialization dataWithJSONObject:jsonRep 
options:0 
error:&error];

现在,您需要对json进行编码。此处定义了所需的编码算法:应用/x-www-form-urlencoded编码算法

这里是实现方法dataFormURLEncodedNSDictionary的一个类别,它返回一个NSData对象,表示作为NSDictionary给出的编码参数(如另一个SO答案所示):如何在HTTP post中向PHP服务器发送多个参数,例如:

NSData* paramsData = [@{@"key": @"value"} dataFormURLEncoded];

"参数字典"需要将NSStrings作为关键字和值。因此,我们需要将JSON(作为NSData)转换为NSString(我们知道它的编码是UTF-8):

NSString* jsonString = [[NSString alloc] initWithData:json 
encoding:NSUTF8StringEncoding];

现在我们可以创建"参数字典:">

NSDictionary* paramsDict = @{@"data": jsonString};

给定链接的SO答案中显示的是NSDictionary类别,我们将参数作为NSData对象,正确编码:

NSData* paramsData = [paramsDict dataFormURLEncoded];

剩下的部分只是创建一个POST请求,这是直接的:

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
[request setURL: url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue: [NSString stringWithFormat:@"%i", [paramsData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: paramsData];

POST和GET 的以下代码

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://url.com/ios/api/get_images_cache.php?"]];
[request setHTTPMethod:@"POST"];
//Here GIVE YOUR PARAMETERS instead of my PARAMETER
NSString *userUpdate =[NSString stringWithFormat:@"email_id=%@&pass=%@",txtEmail.text,txtPass.text,nil];
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data1];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resultStr=[[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(@"resultstr==%@",resultStr);
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER.If you do this clearly you can get the correct results.    
//After that it depends upon the json format whether it is DICTIONARY or ARRAY 
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSString *equalilstr=[dict objectForKey:@"message"];

以下是您的预期答案

第一个编码部分仅用于将数据放入服务

//Here YOUR URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://url.com/ios/api/get_images_cache.php?"]];

//create the Method "GET" or "POST"
[request setHTTPMethod:@"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString strin gWithFormat:@"user_email=%@&user_login=%@&user_pass=%@&  last_upd_by=%@&user_registered=%@&",txtemail.text,txtuser1.text,txtpass1.text,txtuser1.text,datestr,nil];

//Check The Value what we passed
NSLog(@"the data Details is =%@", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(@"got response==%@", resSrt);
if(resSrt)
{
NSLog(@"got response");
/* ViewController *view =[[ViewController alloc]initWithNibName:@"ViewController" bundle:NULL];
[self presentViewController:view animated:YES completion:nil];*/
}
else
{
NSLog(@"faield to connect");
}

第二部分是通过JSON 获取响应

//just give your URL instead of my URL
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL  URLWithString:@"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request   returningResponse:&response error:&err];
//Converting data to String for seeing response
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(@"got response==%@", resSrt);
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER.If you do this clearly you can get the correct results.    
//After that it depends upon the json format whether it is DICTIONARY or ARRAY 
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[[jsonArray objectForKey:@"search_api"]objectForKey:@"result"];

最新更新