C#HTTP POST没有得到的东西WebResponse类 [英] c# http Post not getting anything in webresponse

查看:377
本文介绍了C#HTTP POST没有得到的东西WebResponse类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的请求和响应代码

Here's my code for Request and Response.

System.IO.MemoryStream xmlStream = null;
HttpWebRequest HttpReq = (HttpWebRequest)WebRequest.Create(url); 
xmlStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(format));

byte[] buf2 = xmlStream.ToArray();
System.Text.UTF8Encoding UTF8Enc = new System.Text.UTF8Encoding();
string s = UTF8Enc.GetString(buf2);
string sPost = "XMLData=" + System.Web.HttpUtility.UrlDecode(s);
byte[] bPostData =  UTF8Enc.GetBytes(sPost);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
request.ContentType = "application/x-www-form-urlencoded";
HttpReq.Timeout = 30000;  
request.Method = "POST"; 
request.KeepAlive = true; 
using (Stream requestStream = request.GetRequestStream()) 
{
    requestStream.Write(bPostData, 0, bPostData.Length); 
    requestStream.Close(); 
}

string responseString = "";
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
using (StreamReader sr = new StreamReader(response.GetResponseStream())) 
{ 
    responseString = sr.ReadToEnd(); 
}

这代码崩溃的任何部分。 格式字符串是一个与它的XML。截至去年底,当您尝试,看看有什么在 responseString ,这是一个空字符串。我应该看到的网址发回给我的XML。 ?有什么在此代码缺少

No part of this code crashes. The "format" string is the one with XML in it. By the end when you try to see what's in the responseString, it's an empty string. I am supposed to see the XML sent back to me from the URL. Is there something missing in this code?

推荐答案

我会建议这混乱的代码的简化:

I would recommend a simplification of this messy code:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        { "XMLData", format }
    };
    byte[] resultBuffer = client.UploadValues(url, values);
    string result = Encoding.UTF8.GetString(resultBuffer);
}



如果您希望对XML直接在POST身体上传你不该 T为使用应用程序/ x-WWW窗体-urlencoded 的内容类型。你或许应该指定正确的内容类型,如:使用(VAR的客户=新的WebClient())

and if you wanted to upload the XML directly in the POST body you shouldn't be using application/x-www-form-urlencoded as content type. You probably should specify the correct content type, like this:

using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "text/xml";
    var data = Encoding.UTF8.GetBytes(format);
    byte[] resultBuffer = client.UploadData(url, data);
    string result = Encoding.UTF8.GetString(resultBuffer);
}

这篇关于C#HTTP POST没有得到的东西WebResponse类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆