如何通过HTTP POST从C#调用Web服务

时间:2010-10-10 12:55:35

标签: c# web-services .net-2.0

我想编写一个c#类,它将创建一个连接到运行到www.temp.com的Web服务,向方法DoSomething发送2个字符串参数并获取字符串结果。 我不想使用wsdl。由于我知道网络服务的参数,我只是想做一个简单的电话。

我想在.Net 2中应该有一种简单易用的方法,但我找不到任何例子......

5 个答案:

答案 0 :(得分:22)

如果此“webservice”是一个简单的HTTP GET,您可以使用WebRequest

WebRequest request = WebRequest.Create("http://www.temp.com/?param1=x&param2=y");
request.Method="GET";
WebResponse response = request.GetResponse();

从那里你可以看response.GetResponseStream输出。你可以用同样的方式点击POST服务。

但是,如果这是一个SOAP Web服务,那就不那么容易了。根据webservice的安全性和选项,有时你可以采用已经形成的请求并将其用作模板 - 替换param值并发送它(使用webrequest),然后手动解析SOAP响应......但在这种情况下你正在寻找许多额外的工作,只需使用wsdl.exe来生成代理。

答案 1 :(得分:11)

我会探索将ASP.NET MVC用于您的Web服务。您可以通过标准表单参数提供参数,并将结果作为JSON返回。

[HttpPost]
public ActionResult MyPostAction( string foo, string bar )
{
     ...
     return Json( new { Value = "baz" } );
}

在您的客户端中,使用HttpWebRequest

var request = WebRequest.Create( "/controller/mypostaction" );
request.Method = "POST";
var data = string.Format( "foo={0}&bar={1}", foo, bar );
using (var writer = new StreamWriter( request.GetRequestStream() ))
{
    writer.WriteLine( data );
}
var response = request.GetResponse();
var serializer = new DataContractJsonSerializer(typeof(PostActionResult));
var result = serializer.ReadObject( response.GetResponseStream() )
                 as PostActionResult;

你有

的地方
public class PostActionResult
{
     public string Value { get; set; }
}

答案 2 :(得分:3)

另一种调用POST方法的方法,我曾经在WebAPI中调用POST方法。

            WebClient wc = new WebClient();

            string result;
            wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            result = wc.UploadString("http://localhost:23369/MyController/PostMethodName/Param 1/Param 2","");

            Response.Write(result);

答案 3 :(得分:1)

您可以使用Newtonsoft.Json返回List对象:

WebClient wc = new WebClient();
  string result;
  wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
  var data = string.Format("Value1={0}&Value2={1}&Value3={2}", "param1", "param2", "param3");
  result = wc.UploadString("http:your_services", data);
  var ser = new JavaScriptSerializer();
  var people = ser.Deserialize<object_your[]>(result);

答案 4 :(得分:0)

这是在没有凭据的情况下调用任何服务的静态方法

    /// <summary>
    ///     Connect to service without credentials
    /// </summary>
    /// <param name="url">string url</param>
    /// <param name="requestType">type of request</param>
    /// <param name="objectResult">expected success object result</param>
    /// <param name="objectErrorResult">expected error object result</param>
    /// <param name="objectErrorResultDescription">expected error object description</param>
    /// <param name="body">request body</param>
    /// <param name="bodyType">type of body</param>
    /// <param name="parameters">parameters of request</param>
    /// <returns></returns>
    public static object ConnectToService(string url, string model, RequestType requestType, string objectResult, string objectErrorResult,
                                                      string objectErrorResultDescription, string body = null, string bodyType = null,
                                                      string parameters = null)
    {
        try
        {
            HttpClient client = new HttpClient();
            string tokenEndpoint = url;
            StringContent stringContent;
            string result = string.Empty;

            switch (requestType)
            {
                case RequestType.Get:
                    {
                        var returnRequest = client.GetAsync(tokenEndpoint).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                case RequestType.Post:
                    {
                        stringContent = new StringContent(body, Encoding.UTF8, bodyType);

                        var returnRequest = client.PostAsync(tokenEndpoint, stringContent).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                case RequestType.Put:
                    {
                        stringContent = new StringContent(body, Encoding.UTF8, bodyType);

                        var returnRequest = client.PutAsync(tokenEndpoint, stringContent).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                case RequestType.Delete:
                    {
                        var returnRequest = client.DeleteAsync(tokenEndpoint).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                default:
                    break;
            }

            JObject jobject = !string.IsNullOrEmpty(result) ? JObject.Parse(result) : null;
            var obj = jobject != null ? (jobject[objectResult]?.ToList()?.Count > 0 ? jobject[objectResult]?.ToList() : null) : null;

            return (obj == null && jobject?.ToString() == null && jobject[objectResult]?.ToString() == null) ? throw new Exception(($"{jobject[objectErrorResult]?.ToString()} - {jobject[objectErrorResultDescription]?.ToString()}") ?? (new { Error = new { Code = 400, Message = $"{model} - Requisição inválida." } }).ToString()) : (obj ?? (object)jobject[objectResult]?.ToString()) == null ? jobject : (obj ?? (object)jobject[objectResult]?.ToString());
        }
        catch (NullReferenceException)
        {
            return null;
        }
        catch (Exception e)
        {
            throw new Exception($"{model} - Requisição inválida. Detalhes: {e.Message ?? e.InnerException.Message}");
        }
    }

这是一种使用凭证调用任何服务的静态方法

    /// <summary>
    ///     Connect to service with credentials
    /// </summary>
    /// <param name="url">string url</param>
    /// <param name="requestType">type of request</param>
    /// <param name="handler">credentials</param>
    /// <param name="objectResult">expected success object result</param>
    /// <param name="objectErrorResult">expected error object result</param>
    /// <param name="objectErrorResultDescription">expected error object description</param>
    /// <param name="body">request body</param>
    /// <param name="bodyType">type of body</param>
    /// <param name="parameters">parameters of request</param>
    /// <returns></returns>
    public static object ConnectToService(string url, string model, RequestType requestType, HttpClientHandler handler, string objectResult, string objectErrorResult,
                                                      string objectErrorResultDescription, string body = null, string bodyType = null,
                                                      string parameters = null)
    {
        try
        {
            HttpClient client = new HttpClient(handler);
            string tokenEndpoint = url;
            StringContent stringContent;
            string result = string.Empty;

            switch (requestType)
            {
                case RequestType.Get:
                    {
                        var returnRequest = client.GetAsync(tokenEndpoint).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                case RequestType.Post:
                    {
                        stringContent = new StringContent(body, Encoding.UTF8, bodyType);

                        var returnRequest = client.PostAsync(tokenEndpoint, stringContent).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                case RequestType.Put:
                    {
                        stringContent = new StringContent(body, Encoding.UTF8, bodyType);

                        var returnRequest = client.PutAsync(tokenEndpoint, stringContent).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                case RequestType.Delete:
                    {
                        var returnRequest = client.DeleteAsync(tokenEndpoint).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                default:
                    break;
            }

            JObject jobject = !string.IsNullOrEmpty(result) ? JObject.Parse(result) : null;
            var obj = jobject != null ? (jobject[objectResult]?.ToList()?.Count > 0 ? jobject[objectResult]?.ToList() : null) : null;

            return (obj == null && jobject?.ToString() == null && jobject[objectResult]?.ToString() == null) ? throw new Exception(($"{jobject[objectErrorResult]?.ToString()} - {jobject[objectErrorResultDescription]?.ToString()}") ?? (new { Error = new { Code = 400, Message = $"{model} - Requisição inválida." } }).ToString()) : (obj ?? (object)jobject[objectResult]?.ToString()) == null ? jobject : (obj ?? (object)jobject[objectResult]?.ToString());
        }
        catch (NullReferenceException)
        {
            return null;
        }
        catch (Exception e)
        {
            throw new Exception($"{model} - Invalid request. {e.Message.Split(',')[0] ?? e.InnerException.Message.Split(',')[0]}");
        }
    }