使用身份验证发布Json数据HttpWebRequest HttpWebResponse

时间:2019-07-30 10:53:15

标签: c# json httpwebrequest httpwebresponse

我正在使用HttpWebRequest(C#)使用Restful Web服务从应用程序发布Json数据。为了获得响应,我正在使用HttpWebResponse。每当我在HttpWebRequest对象的GetResponse方法中读取时,都会收到错误“错误请求”。我使用PostMan测试了相同的Json,效果很好。

下面是我的完整代码。

public void MakeJsonString()
{
    StringBuilder JSON = new StringBuilder();

    DataTable dt = new DataTable();
    BLL.ProductsBLL obj = new BLL.ProductsBLL();

    dt = obj.GetPaidOrders();

    //** JSON.Append("{");

    //** JSON.Append("\"Items\":[");
    int ordNo = 1050;
    for (int i = 0; i <= (dt.Rows.Count - 1); i++)
    {
        ordNo++;
        string OrdrTyp = dt.Rows[i]["Type"].ToString().ToLower() == "sample" ? "1" : "2";
        string OrdrStatus = "0";// dt.Rows[i]["Type"].ToString().ToLower() == "sample" ? "1" : "2";
        string dtCardExpDate = dt.Rows[i]["paymode"] == "1" ? Convert.ToDateTime(dt.Rows[0]["CreatedDate"]).ToString("yyyy-MM-dd") : Convert.ToDateTime("1900-01-01").ToString("yyyy-MM-dd");

        //dt.Rows[i][j].ToString();
        JSON.Append("{");
        JSON.Append("\"TrnId\":\"" + ordNo.ToString() + "\", ");
        JSON.Append("\"TrnDte\":\"" + Convert.ToDateTime(dt.Rows[0]["CreatedDate"]).ToString("yyyy-MM-dd") + "\", ");
        JSON.Append("\"FinYer\":\"" + ToFinancialYearShort(Convert.ToDateTime(dt.Rows[i]["CreatedDate"].ToString())) + "\", ");
        JSON.Append("\"OrderType\":\"" + OrdrTyp + "\", ");
        JSON.Append("\"PoNo\":\"" + "" + "\", ");
        JSON.Append("\"CustomerId\":\"" + dt.Rows[i]["id"] + "\", ");
        JSON.Append("\"CacCode\":\"" + dt.Rows[i]["Caccode"] + "\", ");
        JSON.Append("\"AccCode\":\"" + dt.Rows[i]["Acccode"] + "\", ");
        JSON.Append("\"ContactPerson\":\"" + dt.Rows[i]["customername"] + "\", ");
        JSON.Append("\"EmailId\":\"" + dt.Rows[i]["EmailId"] + "\", ");
        JSON.Append("\"CityName\":\"" + dt.Rows[i]["CityName"] + "\", ");
        JSON.Append("\"State\":\"" + dt.Rows[i]["State"] + "\", ");

        JSON.Append("\"ZipCode\":\"" + dt.Rows[i]["zipcode"] + "\", ");
        JSON.Append("\"CountryName\":\"" + dt.Rows[i]["countryname"] + "\", ");
        JSON.Append("\"InvoicePartyAddress\":\"" + dt.Rows[i]["InvoicePartyAddress"] + "\", ");
        JSON.Append("\"NotifyPartyAddress\":\"" + dt.Rows[i]["NotifyPartyAddress"] + "\", ");
        JSON.Append("\"OrgDocPartyAddress\":\"" + dt.Rows[i]["OrgDocPartyAddress"] + "\", ");

        JSON.Append("\"SpecialInstruction\":\"" + dt.Rows[i]["SpecialInstruction"] + "\", ");
        JSON.Append("\"ShipmentMode\":\"" + dt.Rows[i]["ShipmentMode"] + "\", ");
        JSON.Append("\"ShpModeType\":\"" + dt.Rows[i]["ShpModeType"] + "\", ");
        JSON.Append("\"Forwarder\":\"" + dt.Rows[i]["ForwarderID"] + "\", ");
        JSON.Append("\"PortCode\":\"" + dt.Rows[i]["portcode"] + "\", ");
        JSON.Append("\"PayMode\":\"" + dt.Rows[i]["paymode"] + "\", ");
        JSON.Append("\"CreditCardno\":\"" + dt.Rows[i]["Creditcardno"] + "\", ");
        JSON.Append("\"CardExpDate\":\"" + dtCardExpDate + "\", ");
        JSON.Append("\"CardName\":\"" + dt.Rows[i]["Cardname"] + "\", ");
        JSON.Append("\"OrderStatus\":\"" + OrdrStatus + "\", ");

        //JSON.Append("\"paystatus \":\"" + dt.Rows[i]["paystatus"] + "\", ");                                  
        //JSON.Append("\"billingaddress \":\"" + dt.Rows[i]["billingaddress"] + "\", ");
        //JSON.Append("\"shippingaddress \":\"" + dt.Rows[i]["zipcode"] + "\", ");           

        JSON.Append("\"FurtherDiscount\":\"" + dt.Rows[i]["FurtherDiscount"] + "\", ");
        //**JSON.Append("\"FrieghtRate\":\"" + dt.Rows[i]["FreightRate"] + "\", ");
        JSON.Append("\"ForwarderName\":\"" + dt.Rows[i]["customername"] + "\" ");


        JSON.Append("},");       
    }

    if (JSON.ToString().EndsWith(","))
    JSON = JSON.Remove(JSON.Length - 1, 1);

    //** JSON.Append("]}");

    //post to Live server (Push)
    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(@"http://IPADDRESS:PORT/BGradeService-RESTWebService-context-root/rest/v1/setOrderMaster/");


    req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
    req.Credentials = new NetworkCredential("USERNAME", "PASSWORD");

    req.ContentType = "application/vnd.oracle.adf.resourceitem+json"; //"application/vnd.oracle.adf.error+json"; //"application/x-www-form-urlencoded"; //"application/json";
    //req.Accept = "application/json";
    //req.MediaType = "application/json";
    req.Method = "Post";

    //HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

    //WebHeaderCollection header = resp.Headers;

    var encoding = ASCIIEncoding.ASCII;

    //code to post json
    HttpWebResponse response = null;

    JavaScriptSerializer jss = new JavaScriptSerializer();

    var myContent = jss.Serialize(JSON);

    var data = Encoding.ASCII.GetBytes(myContent);


    req.ContentLength = data.Length;

    using (var stream = req.GetRequestStream())
    {
       stream.Write(data, 0, data.Length);
    }

    response = (HttpWebResponse)req.GetResponse(); 
    string ResponseString = "";
    ResponseString = new StreamReader(response.GetResponseStream()).ReadToEnd();


    if (ResponseString != null)
    {
       //Here i will handle the result . i.e. either show it to user or save in database
    }
}

0 个答案:

没有答案