如何解决WebService参数传递中文的问题

很多人在调用WebService所提供方法的时候,发现如果当字符串中含有中文,传到WebService端就发现是乱码,这是由于WebService默认的编码是“UTF-8”,当调用端和接收端用不同编码进行转换的时候,就会出现此类问题,如何解决这类问题呢,具体要根据你的环境而定。

 

如果WebService的代码是你可控的,那么修改起来很简单,只需要把WebService工程中的web.config文件进行修改,即把使用到“utf-8”地方改成“gb2312”就行了。

 

如果WebService的代码是你不可控的,即你无法去修改WebService工程中的web.config文件,那么做起来就比较费事了,就是你需要亲自把当前字符串转换成“UTF-8”的编码,具体如下:

 1     /// <summary>
 2 
 3     /// Change string from default encoding to "UTF-8" encoding
 4 
 5     /// </summary>
 6 
 7     /// <param name="sValue"> the string to be changed </param>
 8 
 9     /// <returns>if changed successfully, return string under "UTF-8" encoding;
10 
11     ///         else return null
12 
13     /// </returns>
14 
15     public static string GetUnicodeString( string sValue )
16 
17     {
18 
19         Encoding def = Encoding.Default;
20 
21         Encoding unicode = Encoding.UTF8;
22 
23        
24 
25         // Check whether default encoding is same as "UTF-8" encoding
26 
27         if( def == unicode ) return sValue;
28 
29  
30 
31         // Check parameter
32 
33         if( sValue == null || sValue.Length == 0 ) return sValue;
34 
35  
36 
37         // Convert the string into a byte[].
38 
39         byte[] defBytes = def.GetBytes( sValue );
40 
41  
42 
43         // Perform the conversion from one encoding to the other.
44 
45         byte[] unicodeBytes = Encoding.Convert( def, unicode, defBytes);
46 
47         char[] uniChars = new char[ unicodeBytes.Length] ;
48 
49         for( int i = 0; i < unicodeBytes.Length; i++ )
50 
51             uniChars[i] = (char)(unicodeBytes[i]);
52 
53  
54 
55         return new string( uniChars );
56 
57     }
58 
59  

       那么调用WebService之前,需要把含有中文的字符串用以上的函数进行转换,然后用转换后的字符串去调用WebService,就可以避免在WebService中出现乱码现象。

posted @ 2013-02-28 10:49  Net-Spider  阅读(1327)  评论(0)    收藏  举报