我正在使用两个链接。第一个链接我创建了 nsaaray ,用于" id"。这个" id"我需要通过第二个链接使用POST方法在 nsurlconnection 中作为参数传递。我尝试了很多,但我在传递参数" id"时卡住了。
nsaaray for id:
- (IBAction)button_drop:(id)sender {
NSString *parseURL =@"first_link";
NSString *encodeurl =[parseURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodeurl];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data){
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
arrMsg = [json valueForKeyPath:@"Branches.branch_name"];
arrmsg1 =[json valueForKeyPath:@"Branches.id"];
[_picker2 reloadAllComponents];
}
}
使用nsurlconnection的POST方法:
NSString *Branchid=@"3";
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:@"GET"]){
NSString *getURL = [NSString stringWithFormat:@"%@?branch_id=%@\n", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(@"%@",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:@"branch_id=%@",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(@"%@", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
}
[request setHTTPMethod:method];
[request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if( connection )
{
mutableData = [NSMutableData new];
}
答案 0 :(得分:0)
尝试创建一个“POST”方法,如下所示: -
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
Branchid, @"branch_id", nil];
NSString *newRequest = [dict JSONRepresentation];
NSData *requestData = [newRequest dataUsingEncoding:NSUTF8StringEncoding];
//If you are not using SBJsonParser Library then try the following:
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *urlString = @"YOUR URL String";
NSURL *requestURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long) [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
mutableData = [NSMutableData new];
}
此外,如果您没有找到正确的答案,可以点击此链接: - Data in POST or GET methods