繁体   English   中英

响应不是来自使用NSURLSession的服务器

[英]Response not coming from server using NSURLSession

我已使用NSURLSession将我的应用程序与服务集成NSURLSession而我的问题是当我使用NSURLConnection向服务器发送请求时,它起作用了,但是当我使用NSURLSession向服务器发送请求时,得到了null响应。 请指教?

我的字典:

 NSDictionary *mainDict = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"" ,@"DocumentNo",
                              dateString ,@"TransDate",
                              CustomerTextField.text ,@"Narration",
                              [NSNumber numberWithInt:3],@"BranchId",
                              [NSNumber numberWithBool:true]  ,@"NewTransaction",
                              addItemsArr ,@"Items",
                              [NSNumber numberWithInt:0] ,@"PartyAcId",
                              @"" ,@"PartyAcCode",
                              [NSNumber numberWithInt:[mainStringvalue intValue]] ,@"SalesPersonId",
                              nil];

NSURLConnection:

NSString *jsonString = [mainDict JSONRepresentation];

NSError *theError = nil;

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSURL *serviceUrl=[NSURL URLWithString:[NSString stringWithFormat:@"my url"]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serviceUrl];
[request setValue:jsonString forHTTPHeaderField:@"json"];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:jsonData];

NSURLResponse *theResponse =[[NSURLResponse alloc]init];

// [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//  [self performSelector:@selector(activityIndicater) withObject:self afterDelay:3];

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];

NSMutableString *string = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"jsonRequest is %@", string);

NSDictionary *jsonDictionaryResponse = [string JSONValue];
NSLog(@"jsonRequest is %@", jsonDictionaryResponse);

NSURLSession:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"mu url"]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:15.0];

                                                          cachePolicy:NSURLRequestUseProtocolCachePolicy

                                                       timeoutInterval:60.0];


//[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];

[request setHTTPBody:jsonData];

//[request setHTTPBody:[self encodeDictionary:params]];

//You now can initiate the request with NSURLSession or NSURLConnection, however you prefer. For example, with NSURLSession, you might do:

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
        NSLog(@"dataTaskWithRequest error: %@", error);
    } else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];

        if (statusCode != 200) {
            NSError *parseError;
            id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
            NSLog(@"responseobject is %@",responseObject);

        } else {
            NSError *parseError;
            id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

            NSLog(@"else condtion");
            if (!responseObject) {
                NSLog(@"JSON parse error: %@", parseError);
            } else {
                NSLog(@"responseobject is %@",responseObject);
                //[self MainService:responseObject];
            }

            //if response was text/html, you might convert it to a string like so:  
            NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"final responseString = %@", responseString);
        }
    }
}];
[task resume];

我遇到了同样的问题,当我在代码中更改HTTPHeaderField值时,我得到了响应。

这是我的示例代码:

NSString *strReqParameters = [NSString stringWithFormat:@"user_email=your_email_id&method=your_methodname"];

NSURL *url = [NSURL URLWithString:@"Your_URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];

[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];

NSData *postData = [strReqParameters dataUsingEncoding:4];

[request setHTTPBody:postData];

NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    //response handler code here
}];

[task resume];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM