可能重复:
Tutorials for using HTTP POST and GET on the iPhone in Objective-C
是否需要创建一个具有正确信息的NSArray,例如id = 1,name = @“John”,得分= 100然后发送它并从服务器接收响应?
可能将其显示在NSLog();
中任何人都可以通过将我链接到一个好的教程来帮助回答这个问题,我也不想使用ASIHTTPRequest。我知道这会更简单,但是如果没有使用预先编写的代码id就可以做一些事情,而是学习如何使用基础框架提供的功能来创建一些东西,然后再使用别人的类。
答案 0 :(得分:2)
您正在寻找的是NSMutableURLRequest和addValue:forHTTPHeaderField方法。
使用您希望与之通信的URL创建请求。将要传输的值加载到标头或HTTPBody中,设置HTTPMethod,然后使用NSURLConnection方法发送和接收响应。
对于包含信息的数组,您可以简单地枚举数组并将值添加到HTTPHeaderFields。这实际上取决于服务器设置接收的内容。
有更多信息。
NSString *urlString = @"http://yoururl.com";
NSURL *url = [NSUL URLWithString:urlString];
NSMutalbeURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSDictionary *headerInformation = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"id",@"John",@"name",@"100",@"score", nil];
for (NSString *key in [headerInformation allKeys])
{
[request addValue:[dict valueForKey:key] forHTTPHeaderField:key];
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
// this will perform a synchronous GET operation passing the values you specified in the header (typically you want asynchrounous, but for simplicity of answering the question it works)
NSData *responseData = [NSURLConnection sendSynchronousRequest:request reuturningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Response: %@", responseString);
[responseString release];
答案 1 :(得分:0)
使用NSData发送网址请求并存储响应然后重新发明轮子可能更容易。这里有一些类似于我的生产项目中的代码:
+ (NSData *)getProfiles {
NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
// Create string of the URL
NSString *serviceURL = [NSString stringWithFormat:@"http://www.myurlhere.com/getProfiles.php?token=%@", token];
NSLog(@"Service URL : %@", serviceURL);
// Create a NSURL out of the string created earlier. Use NSASCIIStringEncoding to make it properly URL encoded (replaces " " with "+", etc)
NSURL *URL = [NSURL URLWithString:[serviceURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
// Request the url and store the response into NSData
NSData *data = [NSData dataWithContentsOfURL:URL];
if (!data) {
return nil;
}
// Since I know the response will be 100% strings, convert the NSData to NSString
NSString *response = [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
// Test response and return a string that an XML Parser can parse
if (![response isEqualToString:@"UNAUTHORIZED"]) {
response = [response stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
data = [response dataUsingEncoding:NSASCIIStringEncoding];
return data;
} else {
return nil;
}
}
NSLog输出:
[Line: 476] +[WebSupport getProfiles]: Service URL : http://www.myurlhere.com/getProfiles.php?token=abcdef0123456789abcdef0123456789