2011-08-25 6 views
3
을 사용하여 POST 데이터

나는 매우 느리게 아이폰 OS 개발을위한 URL 로딩 시스템을 학습을 통해 내 방식을 일하고 있어요, 나는 누군가가 간략하게 다음의 코드 조각 설명 할 수 바라고 : 결국목표 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 Loading System Programming Guide] (http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/)를 읽어 보시기 바랍니다. 10000165i). – jtbandes

1

에 관해서, 그것은으로 대체 할 수 있습니다

당신이 매개 변수 값을 지정하도록 확장 할 수 있도록이 initWithFormat로 작성
NSString *myParameters = @"one=two&three=four"; 

.

두 번째 라인이 HTTP POST 요청입니다 나타냅니다. 당신이 dataUsingEncoding 방법을 사용을 NSData에 문자열 형식을 변환해야하므로

세 번째 라인은 setHTTPBody 방법은있는 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