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

发布于 2024-09-27 00:17:24 字数 182 浏览 0 评论 0原文

我想编写 c# 类,该类将创建与运行到 www.temp.com 的 Web 服务的连接,将 2 个字符串参数发送到方法 DoSomething 并获取字符串结果。 我不想使用 wsdl。因为我知道网络服务的参数,所以我只想进行一个简单的调用。

我想在 .Net 2 中应该有一个简单的方法来做到这一点,但我找不到任何例子......

I want to write a c# class that would create a connection to a webservice running to www.temp.com, send 2 string params to the method DoSomething and get the string result.
I don't want to use wsdl. Since I know the params of the webservice, I just want to make a simple call.

I guess there should be an easy and simple way to do that in .Net 2, but I couldn't find any example...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

行雁书 2024-10-04 00:17:24

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

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

从那里您可以查看 response.GetResponseStream 用于输出。您可以用同样的方式访问 POST 服务。

然而,如果这是一个 SOAP Web 服务,那就没那么容易了。根据 Web 服务的安全性和选项,有时您可以采用已形成的请求并将其用作模板 - 替换参数值并发送它(使用 Webrequest),然后手动解析 SOAP 响应...但在这种情况下您正在考虑大量额外的工作,不妨使用 wsdl.exe 来生成代理。

If this "webservice" is a simple HTTP GET, you can use WebRequest:

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

From there you can look at response.GetResponseStream for the output. You can hit a POST service the same way.

However, if this is a SOAP webservice, it's not quite that easy. Depending on the security and options of the webservice, sometimes you can take an already formed request and use it as a template - replace the param values and send it (using webrequest), then parse the SOAP response manually... but in that case you're looking at lots of extra work an may as well just use wsdl.exe to generate proxies.

没有心的人 2024-10-04 00:17:24

我将探索如何将 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; }
}

I would explore using ASP.NET MVC for your web service. You can provide parameters via the standard form parameters and return the result as JSON.

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

In your client, use the 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;

where you have

public class PostActionResult
{
     public string Value { get; set; }
}
累赘 2024-10-04 00:17:24

另一种调用 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);

One other way to call POST method, I used to call POST method in WebAPI.

            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);
将军与妓 2024-10-04 00:17:24

您可以使用 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);

You can return List object use Newtonsoft.Json:

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);
寂寞清仓 2024-10-04 00:17:24

这是一个无需凭据即可调用任何服务的静态方法

    /// <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]}");
        }
    }

This a static method to call any service without credentials

    /// <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((
quot;{jobject[objectErrorResult]?.ToString()} - {jobject[objectErrorResultDescription]?.ToString()}") ?? (new { Error = new { Code = 400, Message = 
quot;{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(
quot;{model} - Requisição inválida. Detalhes: {e.Message ?? e.InnerException.Message}");
        }
    }

This a static method to call any service with credentials

    /// <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((
quot;{jobject[objectErrorResult]?.ToString()} - {jobject[objectErrorResultDescription]?.ToString()}") ?? (new { Error = new { Code = 400, Message = 
quot;{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(
quot;{model} - Invalid request. {e.Message.Split(',')[0] ?? e.InnerException.Message.Split(',')[0]}");
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文