为什么这个HttpWebRequest形成/合并无法传递正文数据? [英] Why does this HttpWebRequest formation/amalgamation fail to pass the body data along?

查看:70
本文介绍了为什么这个HttpWebRequest形成/合并无法传递正文数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码很完美(AFAIK),但它并没有传递HttpWebRequest中的正文数据:



My code is perfect (AFAIK), but it's not passing along the body data in the HttpWebRequest:

string uri = string.Format("http://192.168.125.50:28642/api/DeliveryItems/PostArgsAndXMLFileAsStr?serialNum={0}&siteNum={1}", serNum, siteNum);
SendXMLFile(fullXMLFilePath, uri);

public static string SendXMLFile(string xmlFilepath, string uri)
{
    StringBuilder sb = new StringBuilder();
    using (StreamReader sr = new StreamReader(xmlFilepath))
    {
        String line;
        while ((line = sr.ReadLine()) != null)
        {
            sb.AppendLine(line);
        }
    }

    string strData = sb.ToString();
    HttpWebRequest request = CreateRequest(uri, HttpMethods.POST, strData, "application/xml");

    request.KeepAlive = false;
    request.ProtocolVersion = HttpVersion.Version10;

    try
    {
        using (var response = (HttpWebResponse)request.GetResponse())
        {
            return response.GetResponseStream().ToString();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("SendXMLFile exception " + ex.Message);
        request.Abort();
        return string.Empty;
    }
}

public static HttpWebRequest CreateRequest(string uri, HttpMethods method, string data, string contentType)
{
    WebRequest request = HttpWebRequest.Create(uri);
    request.Method = Enum.ToObject(typeof(HttpMethods), method).ToString();
    request.ContentType = contentType;
    ((HttpWebRequest)request).Accept = contentType;
    if (method != HttpMethods.GET && method != HttpMethods.DELETE)
    {
        Encoding encoding = Encoding.UTF8;
        request.ContentLength = encoding.GetByteCount(data);
        request.ContentType = contentType;
        request.GetRequestStream().Write(
          encoding.GetBytes(data), 0, (int)request.ContentLength);
        request.GetRequestStream().Close();
    }
    else
    {
        // If we're doing a GET or DELETE don't bother with this
        request.ContentLength = 0;
    }
    // Finally, return the newly created request to the caller.
    return request as HttpWebRequest;
}





以上内容缺少在xmlFilepath中发送文件内容以及HttpWebRequest?



What in the above is lacking to send the contents of the file at xmlFilepath along with the HttpWebRequest?

推荐答案

这篇关于为什么这个HttpWebRequest形成/合并无法传递正文数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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