2016-02-22 2 views
0

Я звоню odata post api, у которого HTTP-заголовок помечен как «form-data». Ниже мой код: -Отправка HTTP POST с запросом данных формы заголовка на iOS

NSURL *restURL = [NSURL URLWithString:urlString]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:restURL]; 
    [request setHTTPMethod: getorpost]; 
    if (jsonData != nil) { 
       [request setValue:@"application/form-data" forHTTPHeaderField:@"Content-Type"]; 

     [request setHTTPBody:jsonData]; 
    } 

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 
    if (connection) { 
     responseData = [[NSMutableData alloc] init]; 
    } 

И я получаю ответ ниже: -

Обработка запроса HTTP привела к исключению. См. Ответ HTTP, возвращенный свойством «Ответ» этого исключения для получения более подробной информации.

Но, он отлично работает в Postman. Кто-нибудь может спросить, где ошибка в моем коде.

Спасибо,

ответ

0

Используйте этот

NSURL *url = [NSURL URLWithString:url_str]; 
NSLog(@"%@",datastring); 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

NSMutableData *requestBody = [[NSMutableData alloc] initWithData:[datastring dataUsingEncoding:NSUTF8StringEncoding]]; 

[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
[request setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"]; 
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestBody length]] forHTTPHeaderField:@"Content-Length"]; 
[request setHTTPBody: requestBody]; 
httpResponse=[[NSHTTPURLResponse alloc]init]; 
receivedData=[[NSMutableData alloc]init]; 
connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 

if(connection) 
{ 
    NSLog(@"%@ calling with datastring: %@", url, datastring); 
} 

делегирует

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 

    httpResponse = (NSHTTPURLResponse *) response; 
    NSLog(@"%d", httpResponse.statusCode); 
     NSLog(@"%@",[httpResponse description]); 

} 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
[receivedData appendData:data]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
receivedData = [[NSMutableData alloc]init]; 
httpResponse=[[NSHTTPURLResponse alloc]init]; 
NSLog(@"%@",[NSString stringWithFormat:@"Connection failed: %@", [error description]]); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
NSError *error; 


NSString *retVal = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]; 
NSLog(@"retVal=%@",retVal); 
} 
+0

это дает мне ту же ошибку. – Sanjay

+0

Какова ваша строка возврата? –

+0

Обработка запроса HTTP привела к исключению. См. Ответ HTTP, возвращаемый свойством «Ответ» этого исключения, для получения более подробной информации. – Sanjay

0
-(void)ViewDidLoad 
{ 
NSMutableDictionary *postData = [[NSMutableDictionary alloc]init]; 
[postData setObject:uid forKey:@"id"]; 
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:postData options:kNilOptions error:nil]; 
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
NSString *post = [[NSString alloc]initWithFormat:@"%@",jsonInputString]; 

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"YOUR URL "]]; 

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

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0]; 
[request setURL:url]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[request setHTTPBody:postData]; 

NSError *error; 
NSURLResponse *response; 
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

NSDictionary *jsonDict; 
if (responseData != nil) 
{ 
    jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; 
    NSLog(@"jsonDoct == %@",jsonDict); 
} 
else 
{ 
    NSLog(@"RESONPSE IS NULL"); 
} 

if (error) 
    { 
     NSLog(@"error %@",error.description); 
    } 
    } 
Смежные вопросы