在C#中使用HTTP请求添加标头和发布数据

时间:2017-03-06 07:00:37

标签: c# .net http restful-authentication

我正在尝试集成API。文档维护我需要在POST下面添加属性标题。但我不知道为什么我的POST代码。我觉得我犯了一个愚蠢的错误。你能看看并帮助我吗?

添加到标题中的属性

  clientId   
  SecurityToken 
  Content-Type 'application/json'
  Accept       `application/json

代码

public string AddOrder(string url, string stringOrder, string bigApiUserID, string BigApiKey)
    {

        try
        {
            string responseStr = "";
            HttpStatusCode statusCode;
            WebRequest request = WebRequest.Create(url);
            request.Credentials = new NetworkCredential(bigApiUserID, BigApiKey);
            request.Method = "POST";
            byte[] bytes;
            bytes = System.Text.Encoding.ASCII.GetBytes(stringOrder);

            request.Headers.Add("SecurityToken", BigApiKey);
            request.ContentType = "application/json";

            request.ContentLength = bytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            statusCode = response.StatusCode;
            if (Convert.ToString(response.StatusCode) == "OK")
            {
                Stream responseStream = response.GetResponseStream();
                responseStr = new StreamReader(responseStream).ReadToEnd();
                return responseStr;
            }
            return responseStr;
        }
        catch (WebException e)
        {

             string responseStr = "";
            using (WebResponse response = e.Response)
            {
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                responseStr = httpResponse.StatusCode.ToString();
                using (Stream data = response.GetResponseStream())
                {
                    responseStr = new StreamReader(data).ReadToEnd();
                }
            }
            ErrorLog errLog = new ErrorLog();
            errLog.LogsWrite(e, Path.GetDirectoryName(Application.ExecutablePath));
            return responseStr;
        }
    }

0 个答案:

没有答案