命令:
curl -X POST -F "search={\"page\":\"1\",\"county\":\"18\",\"type\":\"J\"} " -H "Host: 118932.ro" http://118932.ro/dezv/ipa/index.php
这是我到目前为止所做的:
url = [NSURL URLWithString:@"http://www.118932.ro/dezv/ipa/index.php"];
NSData *data = [NSJSONSerialization dataWithJSONObject:self.requestData options:0 error:&error];
NSString *bodyString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *dataString = [NSString stringWithFormat:@"\"search=%@\"",bodyString];
NSData *dataBody = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:dataBody];
[request setValue:@"118932.ro" forHTTPHeaderField:@"Host"];
其中self.requestData是以下字典
self.requestData = @{@"page" : @"1", @"county" : @"18", @"type" : @"J"};
但在我这样做之后,这似乎没有给我任何结果
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
答案 0 :(得分:1)
这是我使用的代码。 cUrl中的-F参数指定实际的发布数据,因此您可能希望按原样使用字符串"search={\"page\":\"1\",\"county\":\"18\",\"type\":\"J\"} "
。您应该在后台线程中调用此代码,因为同步调用将阻止UI。
/**
* Do an HTTP POST request and return the results
*
* @param NSString * url the URL
* @param NSString * post the POST data
*
* @return NSDictionary * a dictionary containing the response, error, and data
*/
+ (NSDictionary *)httpPostRequestWithUrl:(NSString *)url post:(NSString *)post
{
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", (int)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[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];
[request setTimeoutInterval:30]; // set timeout for 30 seconds
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSMutableDictionary *rc = [[NSMutableDictionary alloc] init];
if ( response )
[rc setObject:response forKey:@"response"];
if ( error )
[rc setObject:error forKey:@"error"];
if ( data )
[rc setObject:data forKey:@"data"];
return (NSDictionary *)rc;
}