我遇到了NSURLConnection,我之前使用它,只是根据请求,获取数据并解析它。但是这次Web开发人员已经开发了GET和POST请求。
我想通过许多教程和堆栈问题,并试图获得所需的结果。 正如我所看到的那样有时候请求,比如
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL"]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[request setHTTPMethod: @"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
我见过的其他人也很少。
我看起来很简单,但我无法找到任何POST和GET请求所需的内容。
我从网络开发者那里收到的数据是
SOAP 1.2
POST /DEMOService/DEMO.asmx HTTP/1.1
Host: projects.demosite.com
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
作为回报,将有GET和POST
以下是HTTP GET请求和响应示例。显示的占位符需要替换为实际值。
GET /DEMOService/DEMO.asmx/VerifyLogin?username=string&password=string&AuthenticationKey=string HTTP/1.1
Host: projects.demosite.com
我很清楚NSURLConnections的代表,他们正在关注......
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
唯一的问题我在哪里?
如何在GET或POST请求中写入传递参数的请求。
由于
答案 0 :(得分:7)
如果您的参数是在URL本身中发送的(例如,作为URL路径或查询字符串的一部分),那么您只需要将它们包含在NSURL参数中。例如,您可能有以下内容:
NSString *urlString = [NSString stringWithFormat:@"https://hostname/DEMOService/DEMO.asmx/VerifyLogin?username=%@&password=%@&AuthenticationKey=%@",
username,
password,
authenticationKey];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
其中username
,password
和authenticationKey
是您在别处设置的局部变量。
来自服务器的响应由NSData
返回的-[NSURLConnection sendSynchronousRequest:returningResponse:error:]
实例中包含的数据存储。
因此,在您的示例中,您上面的回复将存储在response1
变量中。您可以将其转换为字符串和/或根据需要对其进行解析。