When I send a request to my web-service with utf-8 special characters, such as "Ö", it return response 500 "There was an error processing the request" This is what I log in the iOS app.
- (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]);
}
If I send a message with just plain english it works fine.
I'm not sure if the error is on the server-side or in the app itself. This is how I send my 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];
And this is how the web-service look:
....
[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)]
尝试在发送之前进行编码,例如:
NSString *strEncode = [src stringByAddingPercentEscapesUsingEncoding:NSUnicodeStringEncoding];
This line:
self.responseData = [NSData dataWithBytes:[json UTF8String] length:[json length]];
is incorrect. An NSString
's length is in UTF-16 characters, not UTF-8 characters. You could do something like:
const char* utf8 = [json UTF8String];
self.responseData = [NSData dataWithBytes:utf8 length:strlen(utf8)];
but the better way is to just have the string create the NSData
directly, without going through a C-style string.
self.responseData = [json dataUsingEncoding:NSUTF8StringEncoding];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.