Web服务使用HttpWebRequest动态使用不支持的媒体类型

时间:2017-06-16 10:02:20

标签: c# xml web-services system.net.httpwebrequest

public void processVoucher()
{
    try
    {
        string url = "http://192.168.xxx.xx:xxxx/context-root-xxxxxxxx/AccountsPayableManagerPort?WSDL/processVoucher"; 
        StreamReader str = new StreamReader(@"F:\IntelliChief integration to JD Edwards for AP Invoice entry\processVoucher_input_payload.xml");
        string ipParameter = str.ReadToEnd();

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.ContentType = "application/xml";
        req.KeepAlive = true;
        req.Timeout = 30000;
        req.Accept = "application/xml";//"text/xml";
        req.Headers.Clear();
        req.Method = "POST";
        Encoding encode = Encoding.GetEncoding("utf-8");


        using (Stream stm = req.GetRequestStream())
        {
            using (StreamWriter stmw = new StreamWriter(stm))
            {
                stmw.Write(ipParameter);
            }
        }

        var response = req.GetResponse(); // here i am getting Unsupported Media Type issue
        Stream responseStream = response.GetResponseStream();
        StreamReader strReader = new StreamReader(responseStream, encode, true);
        string result = strReader.ReadToEnd();
    }
    catch (Exception ex)
    {

        MessageBox.Show("Error Message:" + ex.Message);
        throw;
    }

}

我要求使用Web服务,显示结果,我正在尝试使用HttpWebRequest类来使用Web服务。我在req.GetResponse()中运行异常,感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

public void processVoucher()         {

        string soap = null;

        try
        {
            StreamReader str = new StreamReader(@"F:\xxx\some.xml");
            soap = str.ReadToEnd();
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://192.168.xxx.xx:xxxx/bla-bla-bla/AccountsPayableManagerPort?WSDL");
            req.ContentType = "text/xml;charset=\"UTF-8\"";
            req.Accept = "text/xml";
            req.Method = "POST";

            using (Stream stm = req.GetRequestStream())
            {
                using (StreamWriter stmw = new StreamWriter(stm))
                {
                    stmw.Write(soap);
                }
            }


            using (WebResponse response = req.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    string soapResult = rd.ReadToEnd();

                }
            }
        }
        catch (Exception)
        {

            throw;
        }

    }

最后我找到了问题的解决方案,上面是工作代码。我改变了 req.ContentType =“application / xml”; to req.ContentType =“text / xml; charset = \”UTF-8 \“”; ,req.Accept =“application / xml”; to req.Accept =“text / xml”; 我删除了req.Headers.Clear(); 我的代码开始工作了感谢所有人的支持......