1. 程式人生 > >C# 後臺使用HttpWebRequest傳送POST請求幫助類

C# 後臺使用HttpWebRequest傳送POST請求幫助類

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

namespace Utils
{
    public class RequestHelper
    {
        public static string SendHttpRequest(string requestURI, string requestMethod, string json)
        {
            //json格式請求資料
            string requestData = json;
            //拼接URL
            string serviceUrl = requestURI;//string.Format("{0}/{1}", requestURI, requestMethod);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //post請求
            myRequest.Method = requestMethod;
            //utf-8編碼
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(requestData);

            myRequest.ContentLength = buf.Length;
            myRequest.Timeout = 5000;
            //指定為json否則會出錯
            myRequest.ContentType = "application/json";
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;
            Stream newStream = myRequest.GetRequestStream();
            newStream.Write(buf, 0, buf.Length);
            newStream.Close();

            //獲得介面返回值
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string ReqResult = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();
            return ReqResult;
        }
    }
}