在C#中将字符串发布到restful webservice

时间:2017-06-27 07:00:11

标签: webservices-client

我提供的网络服务网址类似于: http://ericdev35:7280/persons/persons/ 以及用户名和密码。

我想从WPF应用程序对此Web服务进行调用。 要发送到服务的数据是以下格式的人员的名字和姓氏: 其中 “fname = ABC&安培; L-NAME = XYZ”

如何在C#中调用此方法? 这是我尝试过的代码:

        HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create("http://ericdev35:7280/persons/persons/");
        httpWebRequest.Method = "POST";
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Credentials = new NetworkCredential(username, password);
        string data = "fname=Abc&lname=Xyz";
        StreamWriter writer = new StreamWriter(httpWebRequest.GetRequestStream());
        writer.Write(data);
        writer.Close();

这不会给我任何错误,但我看不到我发布的数据。有什么需要纠正的吗? 内容类型是否正确?

1 个答案:

答案 0 :(得分:0)

此方法发布json。 之后,它获取响应并反序列化Json对象。

private static string PostJson<T1>(string p_url, string p_json, string p_method, out T1 p_target)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(p_url);
    httpWebRequest.UseDefaultCredentials = true;
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = p_method;

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        streamWriter.Write(p_json);
        streamWriter.Flush();
        streamWriter.Close();
    }
    HttpWebResponse httpResponse;
    try
    {
        httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    }
    catch (WebException ex)
    {
        httpResponse = ex.Response as HttpWebResponse;
    }

    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var a_result = streamReader.ReadToEnd();

        //If you dont need a Json object delete anything behind here
        try
        {
            p_target = JsonConvert.DeserializeObject<T1>(a_result);
        }
        catch { p_target = default(T1); }
        return a_result;
    }
}