2011-08-25 43 views
3
POST数据

我非常缓慢地通过学习网址加载系统为iOS开发工作我的方式,我很希望有人能简单介绍一下下面的一段代码:目标C - 使用NSURLConnection的

NSString *myParameters = [[NSString alloc] initWithFormat:@"one=two&three=four"]; 
[myRequest setHTTPMethod:@"POST"]; 
[myRequest setHTTPBody:[myParameters dataUsingEncoding:NSUTF8StringEncoding]]; 

最终我希望能够创建一个登录到我的ISP网站的应用程序,并检索我在本月剩余时间留下了多少数据,并且我觉得我应该首先关注setHTTPMethod/setHTTPBody。

亲切的问候

回答

14

这是一个非常简单的HTTP请求设置;如果你有更具体的问题,你可能会更好地问这些问题。

NSString *myParameters = @"paramOne=valueOne&paramTwo=valueTwo"; 

这设置了一个包含POST参数的字符串。

[myRequest setHTTPMethod:@"POST"]; 

该请求必须是POST request

[myRequest setHTTPBody:[myParameters dataUsingEncoding:NSUTF8StringEncoding]]; 

这将参数放入帖子主体(它们需要是原始数据,所以我们首先将它们编码为UTF-8)。

+0

感谢您的回复。作为后续工作,如果我编写使用用户名和密码登录网站的应用程序,我将如何访问通常由于输入数据而显示的页面数据(即主页面,而不是登录页面)?这与使用NSURLRequest建立NSURLConnection然后下载数据一样简单吗? – achiral

+0

有几种方法。您可以将信息放在[NSURLCredentialStorage](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLCredentialStorage_Class/Reference/Reference.html)中,并将其作为URL,或者使用NSURLConnection委托方法'connection:didReceiveAuthenticationChallenge:'。我强烈建议您查看[URL加载系统编程指南](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/) 10000165i)。 – jtbandes

1

第一行创建了一个字符串,它可以被替换为:

NSString *myParameters = @"one=two&three=four"; 

这是写在initWithFormat这样可以延长它分配的参数值。

第二行表示这是HTTP POST请求。

第三行setHTTPBody方法取NSData类型,所以需要使用dataUsingEncoding方法将字符串类型转换为NSData。

7
Step 1 : set URL definitions: 

// Create the request 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.0.232:8080/xxxx/api/Login"]]; 

    // Specify that it will be a POST request 
    request.HTTPMethod = @"POST"; 

    // This is how we set header fields 
    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 

    NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init]; 

    [postDict setValue:@"Login" forKey:@"methodName"]; 
    [postDict setValue:@"admin" forKey:@"username"]; 
    [postDict setValue:@"123456" forKey:@"password"]; 
    [postDict setValue:@"mobile" forKey:@"clientType"]; 


    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil]; 

    // Checking the format 
    NSString *urlString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 


    // Convert your data and set your request's HTTPBody property 
    NSString *stringData = [[NSString alloc] initWithFormat:@"jsonRequest=%@", urlString]; 

    //@"jsonRequest={\"methodName\":\"Login\",\"username\":\"admin\",\"password\":\"12345678n\",\"clientType\":\"web\"}"; 

    NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding]; 

    request.HTTPBody = requestBodyData; 

    // Create url connection and fire request 
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

    if (!theConnection) { 

     // Release the receivedData object. 
     NSMutableData *responseData = nil; 

     // Inform the user that the connection failed. 
    } 

Step 2: 

// Declare the value for NSURLResponse URL 

//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]; 

    NSError *error=nil; 

    // Convert JSON Object into Dictionary 
    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:_responseData options: 
          NSJSONReadingMutableContainers error:&error]; 



    NSLog(@"Response %@",JSON); 
} 

- (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 
} 
+0

这是演示如何最充分地使用NSURLConnection的答案。 – helsont

0
please use below code. 
+(void)callapi:(NSString *)str withBlock:(dictionary)block{ 

NSData *postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]]; 

NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@“%@/url”,WebserviceUrl]] 
                  cachePolicy:NSURLRequestUseProtocolCachePolicy 
                 timeoutInterval:120.0]; 

[urlRequest setHTTPMethod:@"POST"]; 
[urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[urlRequest setHTTPBody:postData]; 

[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) 
{ 
    if (!data) { 
     NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
      [dict setObject:[NSString stringWithFormat:@"%@",AMLocalizedString(SomethingWentWrong, nil)] forKey:@"error"]; 
     block(dict); 
     return ; 
    } 
    NSError *error = nil; 
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error]; 
    //////NSLog(@"%@",dict); 
    if (!dict) { 
     NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
     [dict setObject:AMLocalizedString(ServerResponceError, nil) forKey:@"error"]; 
     block(dict); 
     return ; 
    } 
    block(dict); 

}]; 
} 
+0

“请尝试下面的代码。”句子不应该在代码块内。此外,请解释您在代码中所做的事情,以便那些对该语言不熟悉的人有机会了解并使用您的代码。 – Wndrr