我的请求正文以UTF-8编码,导致Web服务拒绝它。我有什么选择?

时间:2017-08-27 21:53:01

标签: c# utf-8 httpwebrequest

我正在尝试从Web服务(Salesforce Commerce Cloud)获取令牌,但是因为我的Web客户端正在使用UTF-8对请求进行编码,Content-Length将会出现82个字符..而不是79.因为这个,Web服务正在抛出一个错误。

我尝试将标题更改为application/x-www-form-urlencoded; charset=utf-8但是没有效果。

如果我将我的WebClient从new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8))更改为new StreamWriter(webRequest.GetRequestStream(), Encoding.ASCII)),请求成功,但我不愿意改变它,因为我还有其他东西使用该WebClient并且还不知道他们将如何处理这种变化。

如果没有向我的WebClient添加重载或任何内容,是否有另一种普遍接受的做法是告诉远程Web服务对我的数据进行编码以使其接受它?我假设这在很大程度上取决于Web服务本身的实现。

这是我用来发送请求的方法:

public HttpResponseData SendRequestWithBody(HttpMethod httpMethod, string url, Dictionary<string, string> headers, string contentType, string body)
{
    logger.InfoFormat("Sending {0} request to url={1}", httpMethod.Method, url);

    HttpWebRequest webRequest = CreateHttpWebRequest(url, headers);
    webRequest.ContentType = contentType;
    webRequest.Method = httpMethod.Method;
    ServicePointManager.Expect100Continue = true;

    if (this.webRequestLogger != null)
    {
        webRequestLogger.LogRequest(webRequest, webClientRequestLoggerTime, body);
    }

    using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream(), Encoding.ASCII))
    {
        streamWriter.Write(body);
        streamWriter.Flush();
    }

    HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
    HttpResponseData httpResponseData = CreateHttpResponseData(httpWebResponse);
    if (this.webRequestLogger != null)
    {
        webRequestLogger.LogResponse(httpResponseData, webClientRequestLoggerTime);
    }

    return httpResponseData;
}

    private HttpWebRequest CreateHttpWebRequest(string requestUrl, Dictionary<string, string> headers)
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
        webRequest.Timeout = requestTimeoutInSeconds * 1000;

        if (headers != null && headers.Count > 0)
        {
            foreach (KeyValuePair<string, string> header in headers)
            {
                if (header.Key == HttpHeaderContentTypeName)
                    webRequest.ContentType = header.Value;
                else if (header.Key == HttpHeaderAcceptName)
                    webRequest.Accept = header.Value;
                else
                    webRequest.Headers.Add(header.Key, header.Value);
            }
        }

        return webRequest;
    }

0 个答案:

没有答案