【问题标题】:Do we need to give the request type either "json/xml"我们是否需要提供请求类型“json/xml”
【发布时间】:2013-01-02 00:11:27
【问题描述】:

我的客户获得了一项用于我注册的 Web 服务。我需要发布值。 我正在使用以下代码发布:

-(IBAction)testingPurpose:(id)sender{

    NSMutableDictionary *finalQuoteDict = [[NSMutableDictionary  alloc] init];
    [finalQuoteDict setValue:@"It is an Error Message" forKey:@"ErrorMsg"];
    [finalQuoteDict setValue:@"json" forKey:@"ReturnVal"];
    [finalQuoteDict setValue:@"john@live.com" forKey:@"Email"];
    [finalQuoteDict setValue:@"David John" forKey:@"FullName"];
    [finalQuoteDict setValue:@"2147483647" forKey:@"UserID"];
    [finalQuoteDict setValue:@"john" forKey:@"UserName"];
    [finalQuoteDict setValue:@"qqqqqq" forKey:@"UserPassword"];
    SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];    
    NSString *jsonRequest = [jsonWriter stringWithObject:finalQuoteDict];  
    jsonRequest = [jsonRequest stringByReplacingOccurrencesOfString:@"<" withString:@""];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@Register",MainUrl1,jsonRequest]];
    NSLog(@"url is---%@",url);
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

    NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

    [request setHTTPMethod:@"POST"];

       [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];

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

    NSString *dataString=[[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];
    NSMutableDictionary *getResponseDict = [[NSMutableDictionary alloc] init];
    [getResponseDict addEntriesFromDictionary:[dataString JSONValue]];

}

但它会抛出一个错误说 "错误跟踪是:( "Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"无法识别的前导字符\" UserInfo=0x856ac50 {NSLocalizedDescription=无法识别的前导字符}"

请检查图像,即发布值..

我们是否需要将请求类型指定为“json/xml”

提前非常感谢

【问题讨论】:

    标签: iphone ios objective-c json xml-parsing


    【解决方案1】:

    尝试使用这个 这里 httpMethod 是“POST”。 postData 是您的所有 Post 数据,其 Key 值与 Web 服务请求相同。

    aUrl 是你的服务地址

    -(void)WebService:(NSString *)httpMethod DataDictionary:(id)postData RequestAction:(NSString *)aUrl
    {
        // Check internet Connection
        //Use Reachability class for this==============
            Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
        NetworkStatus internetStatus = [r currentReachabilityStatus];
        if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
        {
          NSLog("No Internet Connection Available");    
               return;
        }
    
        self.identifier = serviceIdentifier;
    
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:aUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0 ];
    
            NSLog(@"final request is %@",request);
    
    
            [request setHTTPMethod:@"POST"];
    
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    //set body in JSON formate
    
            [request setHTTPBody:[[self convertToJSON:postData] dataUsingEncoding:NSUTF8StringEncoding]];  
            NSString    *contentLength = [NSString stringWithFormat:@"%d",[[request HTTPBody] length]]; 
            [request setValue:contentLength forHTTPHeaderField:@"Content-Length"];
    
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    
            if (connection) 
            {
                self.responseData = [NSMutableData data]; //Its a mutable Data object
            }
    }
    
    
    
    //Convert data into JSOn format
    
    //use JSON classes for this 
    -(NSString *)convertToJSON:(id)requestParameters
    {
        NSData *jsonData   = [NSJSONSerialization dataWithJSONObject:requestParameters options:NSJSONWritingPrettyPrinted error:nil];
    
        NSLog(@"JSON DATA LENGTH = %d", [jsonData length]);
    
        NSString *jsonString    = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
        NSLog(@"JSON STR LENGTH = %d", [jsonString length]);
    
        return jsonString;
    
    }
    

    //你会在 NSURLConnection 中得到响应

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        [self.responseData setLength:0];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
    
        [self.responseData appendData:data];
    
    }
    
    
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        NSLog("Failed to get Result......");
    
    
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSString *jsonString = [[[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding] autorelease];
    
        NSDictionary    *aDic = [jsonString JSONValue];
    
       NSLog("Your Response Data is ==>> %d",aDic);
    
    }
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      您不需要在请求类型中提供 json 或 xml,除非或直到 web 服务明确要求它。如果webservice处理就更好了。

      但我认为问题在于解析响应。

      首先确保dataString 不为空或为空,或者您正在从服务器获得一些响应。

      如果它有一些值,那么返回值或服务器响应可能不是有效的 JSON 格式

      您可以通过将 json 响应粘贴到 http://jsonlint.com/.

      【讨论】:

      • 它是一个 .NET post web service .. 我们如何验证?\
      • 您是否从 ios 端的 .NET post web 服务收到任何响应? NSData* 结果中有任何值吗?如果您在 IOS 端收到来自服务器的任何响应,则只需验证该响应。
      猜你喜欢
      • 1970-01-01
      • 2011-08-05
      • 2020-11-30
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      相关资源
      最近更新 更多