1

我正在努力将 POST 方法用于 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()正在向 URL 添加参数?如果没有,如何在 RESTful 服务中向 POST 方法发送多个参数?

另外,如何从文件中读取参数并在 POST 方法中使用?

4

2 回答 2

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();
}
于 2012-10-16T06:32:34.977 回答
0

我不知道您的完整要求是什么,但我强烈的建议是“从简单开始”。

不要使用“Content-type: multipart/form-data”,除非你确定你需要它。相反,从“application/x-www-form-urlencoded”(旧的最爱)或“application/json”(甚至更好)开始。

这是一个很好的分步示例。您可以通过简单的 Google 搜索找到 100 多个:

于 2012-10-16T06:26:43.757 回答