webrequest请求JAVA servlet,webresponse获得返回的压缩后的XML文件,然后再解压处理

//获得压缩流和解压流只能通过byte数组来中间过度,而不能通过字符串来中间过度,因为编码不一致,解压完之后可以将byte数组转换成字符串,注意编码,有中文的话用GB2312或者UTF8试试 private static string GetURlUnZipXML(string Url) { string unzipstr = ""; try { //构造web请求,发送请求,获取响应 WebRequest HttpWebRequest = null; WebResponse HttpWebResponse = null; HttpWebRequest = WebRequest.Create(Url); HttpWebRequest.ContentType = "application/x-www-form-urlencoded"; HttpWebRequest.Method = "Post"; string astr = "<?xml version=/"1.0/" encoding=/"GB2312/"?>" + "<Steel-ERP>" + "<Head SessionID=/"F10D60D350164F66889A8EF8613A19C5/"/>" + "<Body>" + "<Client Job=/"SupContract_List/" ActionName=/"ContractLine_List/">" + "<Where>" + "<Cond ColName=/"CompID/" Op=/"8/" Val=/"2/" Ra=/"/"/>" + "<Cond ColName=/"BizDate/" Op=/"4/" Val=/"2010-2-1/" Ra=/"/"/>" + "<Cond ColName=/"BizDate/" Op=/"5/" Val=/"2010-2-23/" Ra=/"/"/>" + "</Where>" + "</Client>" + "</Body>" + "</Steel-ERP>"; string astr1 = "xml=" + astr + ""; byte[] byteRequest = Encoding.UTF8.GetBytes(astr1); HttpWebRequest.ContentLength = byteRequest.Length; Stream stream = HttpWebRequest.GetRequestStream(); stream.Write(byteRequest, 0, byteRequest.Length); stream.Close(); HttpWebResponse = HttpWebRequest.GetResponse(); MemoryStream ms = new MemoryStream(); Stream res=HttpWebResponse.GetResponseStream(); byte[] buffer = new byte[8192]; while (true) { int read = res.Read(buffer, 0, 8192); if (read == 0) { break; } else { ms.Write(buffer, 0, read); } } HttpWebResponse.Close(); ms.Seek(0, SeekOrigin.Begin); ZipInputStream zis = new ZipInputStream(ms); zis.GetNextEntry();//此行是关键 MemoryStream ms2 = new MemoryStream(); byte[] buf = new byte[8192]; while (true) { int read = zis.Read(buf, 0, buf.Length); if (read == 0) break; ms2.Write(buf, 0, read); } ms2.Seek(0, SeekOrigin.Begin); byte[] buf2 = new byte[ms2.Length]; ms2.Read(buf2, 0, buf2.Length); unzipstr = Encoding.GetEncoding("GB2312").GetString(buf2); } catch (Exception ex) { throw new Exception(ex.Message); } return unzipstr;//返回解压后的字符串 }

调用:

private void button3_Click(object sender, EventArgs e) { string Html = GetURlUnZipXML("http://172.31.2.50:6888/erp/DtServlet"); XmlDocument dom = new XmlDocument(); dom.LoadXml(Html); MessageBox.Show(dom.InnerXml); }

解压用到的是ICSharpCode.SharpZipLib,免费的类库

你可能感兴趣的:(webrequest请求JAVA servlet,webresponse获得返回的压缩后的XML文件,然后再解压处理)