Newer
Older
IRIS_COLLECT / IOM_cs / tool / HttpHelper.cs
yangqianqian on 29 Dec 2020 2 KB first
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using System.Windows.Forms;

namespace IOM_cs.tool
{
    class HttpHelper
    {
        /// <summary>
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method">默认GET,空则补充为GET</param>
        /// <param name="contenttype">默认json,空则补充为json</param>
        /// <param name="header">请求头部</param>
        /// <param name="data">请求body内容</param>
        /// <returns></returns>
        public static string Http(string api,string type, string data, Hashtable header = null)
        {
            string re = "";
            try
            {
                string serverIp = ConfigHelper.GetAppConfig("ServerIp");
                string serverAppPort = ConfigHelper.GetAppConfig("ServerPort");
                string url = "http://" + serverIp + ":" + serverAppPort + api;


                string contenttype = "application/json;charset=utf-8";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = type;
                request.ContentType = string.IsNullOrEmpty(contenttype) ? "application/json;charset=utf-8" : contenttype;
                if (header != null)
                {
                    foreach (var i in header.Keys)
                    {
                        request.Headers.Add(i.ToString(), header[i].ToString());
                    }
                }
                if (!string.IsNullOrEmpty(data))
                {
                    Stream RequestStream = request.GetRequestStream();
                    byte[] bytes = Encoding.UTF8.GetBytes(data);
                    RequestStream.Write(bytes, 0, bytes.Length);
                    RequestStream.Close();
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream ResponseStream = response.GetResponseStream();
                StreamReader StreamReader = new StreamReader(ResponseStream, Encoding.GetEncoding("utf-8"));
                re = StreamReader.ReadToEnd();
                StreamReader.Close();
                ResponseStream.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("访问服务器异常!"+ ex.Message);
                return re;
            }
            return re;
        }
    }
}