如何在目标 c 中将 SOAP 数据发布到服务器

Posted

技术标签:

【中文标题】如何在目标 c 中将 SOAP 数据发布到服务器【英文标题】:How to post SOAP data to server in objective c 【发布时间】:2016-06-28 11:13:03 【问题描述】:

我正在尝试将数据发布到服务器,但它给了我错误 代码是

-(IBAction)loginBtnClk:(id)sender

  [self sendDataToServer :@"POST"];


-(void) sendDataToServer : (NSString *) method

    int UserId=0;
    NSString *UserCode  = userTf.text;
    int RoleId=12;
    NSString *Salutation = @"Mr.";
    NSString *FirstName=frstnmetf.text;
    NSString *LastName =lstnametf.text;
    NSString *Pwd=paswrdTf.text;
    NSString *EmailId=@"abc@gmail.com";
    NSString *Mobile=@"9876543210";
    NSString *UserType=@"4";
    int EmpId=0;
    int ZoneId=575;

    NSString *post = [NSString stringWithFormat:@"UserId=%d&UserCode=%@&RoleId=%d&Salutation=%@&FirstName=%@&LastName=%@&Pwd=%@EmailId=%@&Mobile=%@&UserType=%@&EmpId=%d&ZoneId=%d",UserId,UserCode,RoleId,Salutation,FirstName,LastName,Pwd,EmailId,Mobile,UserType,EmpId,ZoneId];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[post length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://URL?op=Insert_UserData"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    NSLog(@"URL = %@",request);
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    NSLog(@"Connection link =%@",conn);
    if(conn) 
        mutableData =[[NSMutableData alloc] init];
        NSLog(@"Connection Successful");
     else 
        NSLog(@"Connection could not be made");
    



#pragma mark NSURLConnection delegates

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

    [mutableData setLength:0];


-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

    [mutableData appendData:data];


-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

    serverResponse.text = NO_CONNECTION;
    return;


-(void)connectionDidFinishLoading:(NSURLConnection *)connection


    NSXMLParser *myNSXMLParserfloorObj=[[NSXMLParser alloc]initWithData:mutableData];
    myNSXMLParserfloorObj.delegate=self;
    [myNSXMLParserfloorObj parse];
    NSLog(@"%@",myNSXMLParserfloorObj.parserError);
    NSString *responseStringWithEncoded = [[NSString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
    //NSLog(@"Response from Server : %@", responseStringWithEncoded);
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:@ NSDocumentTypeDocumentAttribute: NShtmlTextDocumentType  documentAttributes:nil error:nil];
    serverResponse.attributedText = attrStr;

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict

    if([elementName isEqualToString:@"Insert_UserData"])
    
        myDataClassObj=[[mydata alloc]init];
    

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

    myMutableStringObj=[[NSMutableString alloc]initWithString:string];
    NSLog(@"Array String: %@",myMutableStringObj);
    NSData *data = [myMutableStringObj dataUsingEncoding:NSUTF8StringEncoding];
    responsedict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"JSON DATA = %@",responsedict);



-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName



当我尝试发布数据时,它显示错误

2016-06-28 16:37:07.793 WebServiceDemo[5407:137315] Connection Successful
2016-06-28 16:37:13.035 WebServiceDemo[5407:137315] Array String: soap:Receiver
2016-06-28 16:37:13.035 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:15.241 WebServiceDemo[5407:137315] Array String: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---
2016-06-28 16:37:15.242 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:17.680 WebServiceDemo[5407:137315] Array String: >
2016-06-28 16:37:17.680 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:19.835 WebServiceDemo[5407:137315] Array String:  System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
2016-06-28 16:37:19.835 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:21.555 WebServiceDemo[5407:137315] Array String: 
   at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
2016-06-28 16:37:21.556 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:22.808 WebServiceDemo[5407:137315] Array String: 
   at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
2016-06-28 16:37:22.808 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:23.810 WebServiceDemo[5407:137315] Array String: 
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
2016-06-28 16:37:23.811 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:24.696 WebServiceDemo[5407:137315] Array String: 
   at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
2016-06-28 16:37:24.696 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:25.532 WebServiceDemo[5407:137315] Array String: 
   at System.Xml.XmlReader.MoveToContent()
2016-06-28 16:37:25.532 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:26.200 WebServiceDemo[5407:137315] Array String: 
   at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
2016-06-28 16:37:26.200 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:26.986 WebServiceDemo[5407:137315] Array String: 
   at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
2016-06-28 16:37:26.986 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:27.820 WebServiceDemo[5407:137315] Array String: 
   at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
2016-06-28 16:37:27.820 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:28.705 WebServiceDemo[5407:137315] Array String: 
   at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
2016-06-28 16:37:28.705 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:29.474 WebServiceDemo[5407:137315] Array String: 
   at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean
2016-06-28 16:37:29.475 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:30.309 WebServiceDemo[5407:137315] Array String: &
2016-06-28 16:37:30.309 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:31.129 WebServiceDemo[5407:137315] Array String:  abortProcessing)
2016-06-28 16:37:31.130 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:31.881 WebServiceDemo[5407:137315] Array String: 
   --- End of inner exception stack trace ---
2016-06-28 16:37:31.882 WebServiceDemo[5407:137315] JSON DATA = (null)
2016-06-28 16:37:31.882 WebServiceDemo[5407:137315] (null)

我不明白问题所在。数据已从服务器正确检索,但在发布时显示错误。 帮我。

【问题讨论】:

出于调试目的,如果您可以在解析之前打印整个接收到的数据,将会很有帮助。从解析的片段来看,看起来 Web 服务正在期待一个不同的请求,即一些 XML 正文而不是 URL 编码值列表。 那么如何将 URL 编码的值转换为 XML 正文。 @"yoururl.com\">\n" "%@\n" "%@\n " "%@\n" "\n" @Bhadresh 我也试过了。但它显示了同样的错误。 您需要有关有效请求应该是什么样子的信息。我们无法向您提供此信息,因为这是特定于 Web 服务的,我们不知道您正在使用什么 Web 服务。 @BhadreshKathiriya 的评论只是一个很可能是错误的猜测。与负责 Web 服务的人员交谈。他们会知道的。 【参考方案1】:

它终于运行了。只是我改了代码

-(IBAction)sendDataUsingGet:(id)sender

    [self sendDataToServer : @"GET"];

-(void) sendDataToServer : (NSString *) method

    int UserId=idtxt.text;
    NSString *UserCode  = userTf.text;

    NSString *soapMessage = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                             "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                             "<soap:Body>"
                             "<Method xmlns=\"http://tempuri.org/\">"
                             "<Paramener1>%d</Paramener1>"
                             "<Paramener2>%@</Paramener2>"
                             "</Method>"
                             "</soap:Body>"
                             "</soap:Envelope>",UserId,UserCode];

    NSData *postData = [soapMessage dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[soapMessage length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://URL/Method"]];
    [request setHTTPMethod:@"POST"];
    [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    NSLog(@"URL = %@",request);
    //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    NSLog(@"Connection link =%@",conn);
    if(conn) 
        mutableData =[[NSMutableData alloc] init];
        NSLog(@"Connection Successful");
     else 
        NSLog(@"Connection could not be made");
    



#pragma mark NSURLConnection delegates

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

    [mutableData setLength:0];


-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

    [mutableData appendData:data];


-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

    serverResponse.text = NO_CONNECTION;
    return;

-(void)connectionDidFinishLoading:(NSURLConnection *)connection


    NSXMLParser *myNSXMLParserfloorObj=[[NSXMLParser alloc]initWithData:mutableData];
    myNSXMLParserfloorObj.delegate=self;
    [myNSXMLParserfloorObj parse];
    NSLog(@"%@",myNSXMLParserfloorObj.parserError);
    NSString *responseStringWithEncoded = [[NSString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
    //NSLog(@"Response from Server : %@", responseStringWithEncoded);
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:@ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType  documentAttributes:nil error:nil];
    serverResponse.attributedText = attrStr;

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict

    if([elementName isEqualToString:@"Insert_UserData"])
    
        myDataClassObj=[[mydata alloc]init];
    

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

    myMutableStringObj=[[NSMutableString alloc]initWithString:string];
    NSLog(@"Array String: %@",myMutableStringObj);
    NSData *data = [myMutableStringObj dataUsingEncoding:NSUTF8StringEncoding];
    responsedict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"JSON DATA = %@",responsedict);



-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName



【讨论】:

【参考方案2】:
Please be serialize the data before you will send

     NSURL *URL = [NSURL URLWithString:@"URL"];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
            [request setValue:[NSString stringWithFormat:@"application/json"] forHTTPHeaderField:@"Content-Type"];
            [request setHTTPMethod:@"POST"];


            NSMutableArray *myArray = [[NSMutableArray alloc] init];
            [myArray addObject:param];

            NSError * err;
            NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:0 error:&err];


            NSMutableData *postBody = [NSMutableData data];
            [postBody appendData:jsonData];

            //add the body to the post
            [request setHTTPBody:postBody];



    //    NSURL *URL = [NSURL URLWithString:@"URL"];
    //    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    //    [request setValue:[NSString stringWithFormat:@"application/raw"] forHTTPHeaderField:@"Content-Type"];
    //    [request setHTTPMethod:@"GET"];


        //    UploadDataCmd dataCmd = (UploadDataCmd )cmd;
        //    dataCmd.resource = [MyEFAPIResource getUploadMePhotoResource:param];
            AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                                 initWithRequest:request];
            operation.responseSerializer = [AFJSONResponseSerializer serializer];
            [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
             
                 //[dataCmd filterData:responseObject];
                 NSLog(@"Pushed Done");
              failure:^(AFHTTPRequestOperation operation, NSError error)
             
                 //[dataCmd showError:error];
                  NSLog(@"Not Pushed");
             ];
            [operation start];

【讨论】:

什么是 AFHTTPRequestOperation ??

以上是关于如何在目标 c 中将 SOAP 数据发布到服务器的主要内容,如果未能解决你的问题,请参考以下文章

如何在 ios 中将变量从 javascript 传递到目标 C 和目标 C 到 Javascript

如何在ssis中将多个文件加载到多个目标表中

在 Java 中将 WireMock 与 SOAP Web 服务一起使用

如何在 Android SOAP Webservices 中将 InputStream 数据转换为字符串

IOS如何在目标c中将AFNetworking添加到我的xcode项目中

如何在iOS(目标C)中将字符从一个位置修剪到另一个位置?