我很难将REST方法用于RESTful服务。我的要求是我需要追加的一些参数(不在URL中)和我需要从文件中读取的2个参数。该服务是用Java编写的。
string url= "http://srfmdpimd2:18109/1010-SF-TNTIN/Configurator/rest/importConfiguration/"
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
FileStream file = new FileStream(@"TestSCDS.properties", FileMode.Open);
Byte[] bytes = new Byte[file.Length];
file.Read(bytes, 0, bytes.Length);
string strresponse = Encoding.UTF8.GetString(bytes);
request.Method = "POST";
request.ContentType = "multipart/form-data;";
request.ContentLength = file.Length;
request.Headers.Add("hhrr", "H010");
request.Headers.Add("env", "TEST");
request.Headers.Add("buildLabel", "TNTAL_05.05.0500_C54");
Stream Postdata = request.GetRequestStream();
Postdata.Write(bytes, 0, bytes.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();`
request.Headers.Add()
正在向网址添加参数?如果没有,我如何在restful服务中向POST方法发送多个参数?
另外,如何从文件中读取参数并在POST方法中使用?
答案 0 :(得分:1)
它需要一点腿部工作,编码字典并将其放入体内。以下是一个快速示例:
private string Send(string url)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
string postData = EncodeDictionary(args, false);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] postDataBytes = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataBytes.Length;
using(Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
private string EncodeDictionary(Dictionary<string, string> dict,
bool questionMark)
{
StringBuilder sb = new StringBuilder();
if (questionMark)
{
sb.Append("?");
}
foreach (KeyValuePair<string, string> kvp in dict)
{
sb.Append(HttpUtility.UrlEncode(kvp.Key));
sb.Append("=");
sb.Append(HttpUtility.UrlEncode(kvp.Value));
sb.Append("&");
}
sb.Remove(sb.Length - 1, 1); // Remove trailing &
return sb.ToString();
}
答案 1 :(得分:0)
我不知道你的完整要求是什么,但我的强烈建议是“开始简单”。
不使用“内容类型:multipart / form-data”,除非您确定需要它。相反,从“application / x-www-form-urlencoded”(旧的最爱)或“application / json”开始(甚至更好)。
这是一个很好的小步骤示例。通过简单的Google搜索,你可以找到100多个字母: