我想通过网络服务进行创建,需要像这样的uri:
http://<url>/webservice.php?operation=<operation>&elementType=<elementType>&element=<element>&
我的问题是,element是带有html正文的电子邮件的全部信息,大约6000个字符
我想这样称呼网址:
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太长了。
我无法更改服务器的网址最大长度,网络服务需要网址中的参数。
我还没有为我找到合适的解决方案,所以任何帮助都表示赞赏。
更新
对于任何面临同样问题的人来说,对我有用的解决方案是将我的查询放入像
var encoding = new UTF8Encoding();
byte[] bytes = enconding.GetBytes((queryString));
并将其写入webrequest而不是我的queryString
var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
答案 0 :(得分:1)
您可以使用以下内容将数据放入请求的正文中:
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的,但可以是你想传递的任何内容......这是一个简单的例子,希望能让你了解如何继续。
答案 1 :(得分:1)
您需要在问号处拆分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();
祝你好运。