0

我的客户获得了一项用于我注册的 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]];

}

但它抛出一个错误说 “错误跟踪是:(“错误域=org.brautaset.JSON.ErrorDomain代码=3\”无法识别的前导字符\“用户信息=0x856ac50 {NSLocalizedDescription=无法识别的前导字符}”

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

我们是否需要提供请求类型“json/xml”

在此处输入图像描述

非常感谢提前

4

2 回答 2

0

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

aUrl 是你的服务 url

-(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);

}

希望这会帮助你

于 2013-01-18T10:09:44.967 回答
0

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

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

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

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

您可以通过将 json 响应粘贴到 http://jsonlint.com/来验证它。

于 2013-01-18T10:07:49.210 回答