Цель C - POST-данные с использованием NSURLConnection - PullRequest
3 голосов
/ 25 августа 2011

Я очень медленно прорабатываю систему загрузки URL для разработки под iOS, и я надеюсь, что кто-то может кратко объяснить следующий фрагмент кода:

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

В конечном итоге я хотел бы иметь возможность создать приложение, которое регистрируется на веб-сайте моего интернет-провайдера и извлекает объем данных, оставшихся у меня на оставшуюся часть месяца, и я чувствую, что мне нужно сначала разобраться с setHTTPMethod / setHTTPBody .

С уважением

Ответы [ 4 ]

14 голосов
/ 25 августа 2011

Это довольно простая настройка HTTP-запроса;если у вас есть более конкретные вопросы, вам лучше задать их.

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

Это устанавливает строку, содержащую параметры POST.

[myRequest setHTTPMethod:@"POST"];

Запрос должен быть POST-запрос .

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

Это помещает параметры в тело сообщения (они должны быть необработанными данными, поэтому мы сначала закодируем их как UTF-8).

7 голосов
/ 23 сентября 2014
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
}
1 голос
/ 25 августа 2011

Первая строка создала строку, ее можно заменить на:

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

Он написан в initWithFormat, так что вы можете расширить его, чтобы назначить значение параметра.

Вторая строка указывает, что это HTTP пост-запрос.

Третья строка, метод setHTTPBody, принимает тип NSData, поэтому вам необходимо преобразовать строковый тип в NSData, используя метод dataUsingEncoding.

0 голосов
/ 23 октября 2017
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);

 }];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...