Web服务的请求uri太长

本文关键字:uri 太长 请求 服务 Web | 更新日期: 2023-09-27 18:25:45

我想通过Web服务进行创建,该服务需要这样的uri:

http://<url>/webservice.php?operation=<operation>&elementType=<elementType>&element=<element>&

我的问题是,元素是一封html正文的电子邮件的所有信息,大约有6000个字符
我想这样调用url:

var request = WebRequest.Create(urlToUse.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = urlToUse.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(urlToUse);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();

但它在上坏了

var response = request.GetResponse();

并表示uri太长

我无法更改服务器url的最大长度,Web服务需要url中的参数
我还没有找到适合我的解决方案,所以我们非常感谢您的帮助

更新:
对于任何面临相同问题的人,对我有效的解决方案是将我的查询放入字节数组中,如

var encoding = new UTF8Encoding();
byte[] bytes = enconding.GetBytes((queryString));

并将其写入webrequest,而不是我的queryString

var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);

Web服务的请求uri太长

您可以将数据放在请求的正文中,方法有点类似:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://<url>/webservice.php");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var jsonContent = JsonConvert.SerializeObject(new YourObject
    {
        // Pseudo code... Replace <...> with your values etc
        Operation = <YourOperation>,
        ElementType = <YourElementType>,
        Element = <YourElement>,
        // etc...
    });
    HttpResponseMessage response;
    using (HttpContent httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
    {
        response = await client.PostAsync("youroperation/", httpContent);
    }
    // Do something with response if you want
}

这是基于JSON的,但可以是您想要传递的任何内容……这是一个简单的示例,有望让您了解如何继续。

您需要在问号处拆分urlToUse:

类似这样的东西(未测试)

string[] parts = urlToUse.ToString().Split(new char[]{'?'}, 2);
string url = parts[0];
string data = parts[1];
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(data);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();

祝你的任务顺利。