简体   繁体   中英

How can I call a webservice from C# with HTTP POST

I want to write ac# 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...

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

WebRequest request = WebRequest.Create("http://www.temp.com/?param1=x&param2=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.

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; }
}

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);

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);

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(($"{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}");
        }
    }

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(($"{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]}");
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM