使用c#Httprequest发布json数据

时间:2015-08-03 12:46:32

标签: c# asp.net json httprequest c#-2.0

我试图将json数据发布到URL。我的请求数据结构是

方法名称:PAYTYPE

{ id: "string",uid: "string", pwd: "string", apiKey: "string",paymentCategory: int, paymentType: int }

我需要发送一个名为SIGNATURE的标题以及此数据,签名的值是加密请求数据。但我不知道如何添加标题(SIGNATURE)和方法名称(PAYTYPE)和值(加密数据) )发布。 我做过类似的事情

    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("URL");
    httpWebRequest.ContentType = "text/json";
    httpWebRequest.Method = "POST";
    httpWebRequest.Headers.Add("PAYTYPE", "SIGNATURE"+sEncrypteddata)
    using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = "{\"id\":\"2423432432\"," +
                      "\"uid\":\"id123\","+
                      "\"pwd\":\"pass\","+
                      "\"apiKey\":\"2423432432\","+
                      "\"paymentCategory\":0"+
                       "\"paymentType\":0}";

        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
    }
    System.Net.ServicePointManager.Expect100Continue = false;
    HttpWebResponse  httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        string result = streamReader.ReadToEnd();
    }

Iam得到异常"远程服务器返回错误:(405)方法不允许。"

如果代码结构为Ok,那么我想知道如何为此添加标题,签名和值,或者是否还有其他步骤。

1 个答案:

答案 0 :(得分:0)

尝试在添加自定义标头之前添加此行:

httpWebRequest.GetResponse();