所以我试图通过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"];
我删除了它们,最后我开始工作了,谢谢!
答案 0 :(得分:0)
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];
答案 1 :(得分:0)
这是您的预期答案
第一个编码部分仅用于将数据发送到服务器
//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"];
答案 2 :(得分:0)
您可以在POST请求中使用application/x-www-form-urlencoded
,您可以在其中发送许多参数(键/值对)。
请注意,必须正确编码参数键和值。特别是,JSON通常包含许多不能用作参数值的字符。
因此,给定一个代表您的JSON的对象 jsonRep ,它是NSArray
或NSDictionary
对象,您将得到JSON:
NSError* error;
NSData* json = [NSJSONSerialization dataWithJSONObject:jsonRep
options:0
error:&error];
现在,您需要编码 json。所需的编码算法在此处定义: The application/x-www-form-urlencoded encoding algorithm
这是NSDictionary
实现方法dataFormURLEncoded
的类别,它返回一个NSData
对象,表示编码参数,以NSDictionary
形式给出(在另一个SO答案中显示) ):How to send multiple parameterts to PHP server in HTTP post,例如:
NSData* paramsData = [@{@"key": @"value"} dataFormURLEncoded];
"参数词典"需要NSString
作为键和值。因此,我们需要将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];
答案 3 :(得分:0)
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"];