在与一个第三方接口对接时,发现对方无法用GZip解压我发过去的数据,看了对方PHP的示例代码,发现对方使用的是PHP的$file = iconv("IOS-8859-1","UTF-8",gzencode($data_json));大致意思是要先压缩,在把压缩的数组,转成ISO-8859-1的字符串再发送。
那么c#没有iconv这样的方法,根据他的意思最终这样操作后对方可以正常解压我发送的数据了。
/// <summary>
/// GZip加密后的POST请求
/// </summary>
/// <param name="jsonData">Json内容</param>
/// <returns></returns>
public static string Post(string jsonData) {
var strBytes = Encoding.UTF8.GetBytes(jsonData);
byte[] compressedBytes = GZzipCompress(strBytes);//GZip压缩
var str = Encoding.GetEncoding("ISO-8859-1").GetString(compressedBytes);//先转成ISO-8859-1的字符串
var postBytes = Encoding.UTF8.GetBytes(str);
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("");
webrequest.Method = "POST";
webrequest.ContentLength = postBytes.Length;
using (var stream = webrequest.GetRequestStream()) {
stream.Write(postBytes, 0, postBytes.Length);
}
using (var httpWebResponse = (HttpWebResponse)webrequest.GetResponse())
{
using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
{
var ret = responseStream.ReadToEnd();
return ret;
}
}
}