后端服务器请求

定义 Uri (注意Uri写法):

 Uri urlthree = new Uri("http://cloud.calmcar.com/data/api/vboxpush.action");

定义一个byte[] data 数组:

  byte[] sssss = System.Text.Encoding.UTF8.GetBytes("fdsafdsafdsa");

byte 与string 的转换:

 string ssssssssss= System.Text.Encoding.UTF8.GetString(sssss);

服务器后端请求的发送:

public static string Http(Uri uri, byte[] data = null)
        {
            string rtnVal = "";
            int tryTimes = 0;
        again:
            tryTimes++;
            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(uri);
                webRequest.Method = "GET";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                if (data != null)
                {
                    webRequest.Method = "POST";
                    webRequest.ContentLength = data.Length;
                    Stream inputStream = webRequest.GetRequestStream();
                    inputStream.Write(data, 0, data.Length);
                    inputStream.Close();
                    inputStream.Dispose();
                    inputStream = null;
                }
                HttpWebResponse webResp = (HttpWebResponse)webRequest.GetResponse();
                using (Stream receiveStream = webResp.GetResponseStream())
                {
                    using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                    {
                        rtnVal = readStream.ReadToEnd();
                    }
                }
            }
            catch (Exception)
            {
                if (tryTimes < 1) goto again;
            }
            return rtnVal;
        }
    }
} 

 

posted @ 2018-10-12 16:01  Hfox  Views(82)  Comments(0)    收藏  举报