发送utf-8时响应500

时间:2012-05-16 09:43:17

标签: c# objective-c ios asp.net-mvc-3

当我使用utf-8特殊字符(例如“Ö”)向我的网络服务发送请求时,它会返回响应500“处理请求时出错”这是我在iOS应用程序中登录的内容。< / p>

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

    dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:self.responseData error:&error];
    for (id key in dict) {
        NSLog(@"%@=%@", key, [dict objectForKey:key]);
    }

如果我发送的信息只是简单的英语,那就可以了。

我不确定错误是在服务器端还是在应用程序本身。 这就是我发送JSON POST的方式:

    - (void)stringWithUrl:(NSURL *)url jsonReq:(NSString *)json{

    self.requestURL = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease];
    self.responseData = [NSData dataWithBytes:[json UTF8String] length:[json length]];


    [self.requestURL setHTTPMethod:@"POST"];
    [self.requestURL setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [self.requestURL setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [self.requestURL setValue:@"application/json" forHTTPHeaderField:@"UTF-8"];
    [self.requestURL setValue:[NSString stringWithFormat:@"%d", [self.responseData length]] forHTTPHeaderField:@"Content-Length"];
    [self.requestURL setHTTPBody: self.responseData];

这就是网络服务的外观:

    ....    
[WebService(Namespace = "http://mypage.com/webservicesF")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX,
    [System.Web.Script.Services.ScriptService]
.....
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

2 个答案:

答案 0 :(得分:0)

在发送之前尝试编码,如:

    NSString *strEncode =  [src stringByAddingPercentEscapesUsingEncoding:NSUnicodeStringEncoding];

答案 1 :(得分:0)

这一行:

self.responseData = [NSData dataWithBytes:[json UTF8String] length:[json length]];

不正确。 NSString的长度为UTF-16字符,而不是UTF-8字符。你可以这样做:

const char* utf8 = [json UTF8String];
self.responseData = [NSData dataWithBytes:utf8 length:strlen(utf8)];

但更好的方法是让字符串直接创建NSData,而不通过C风格的字符串。

self.responseData = [json dataUsingEncoding:NSUTF8StringEncoding];