C # POST with exception handling

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Bst.PulgIn
{
    public static  class PostHelp
    {
        /// <summary>
        /// POST整个字符串到URL地址中
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="jsonParas"></param>
        /// <returns></returns>
        public static string PostUrl(string Url, string jsonParas)
        {
            string strURL = Url;

            // Create an HTTP request 
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create (strURL);
            // Post request method 
            request.Method = "POST";
            // Content type
            request.ContentType = "application / x-www-form-urlencoded ";

            // Set parameters and URL encode

            string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas); 

            byte [] payload;
            // Convert Json string into byte 
            payload = System.Text.Encoding.UTF8.GetBytes (paraUrlCoded);
            // Set the requested ContentLength 
            request.ContentLength = payload.Length;
            // Send the request Request flow

            Stream writer;
            try
            {
                writer = request.GetRequestStream (); // Get the Stream object used to write the request data
            }
            catch (Exception)
            {
                writer = null;
                Console.Write ("Failed to connect to the server!");
            }
            // Write the request parameters to the stream
            writer.Write (payload, 0, payload.Length);
            writer.Close (); // Close the request stream

            // String strValue = ""; // strValue is the character stream returned by http response
            HttpWebResponse response;
            try
            {
                // Get response stream
                response = (HttpWebResponse) request.GetResponse ();
            }
            catch (WebException ex)
            {
                response = ex .Response as HttpWebResponse;
            }

            Stream s = response.GetResponseStream();

            //  Stream postData = System.Web.HttpContext.Current.Request.InputStream;
            StreamReader sRead = new StreamReader(s);
            string postContent = sRead.ReadToEnd();
            sRead.Close();

            return postContent; // Return Json data
        }
    }
}
 

Published 21 original articles · 21 praises · 40,000+ views

Guess you like

Origin blog.csdn.net/kuyz1/article/details/88220648