组织http请求
post方式
string stratTime=""; string end=""://要拼接的参数 string postURL = "http://www.baidu.com?startTime=" + start + "&endTime=" + end; Encoding dataEncode=Encoding.UTF8;//声明字符格式 byte[] by=dataEncode.GetBytes(postURL);//url转换 HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postURL)); webReq.Method = "post"; webReq.ContentType = "application/json"; webReq.ContentLength = byteArray.Length; Stream newStream = webReq.GetRequestStream(); newStream.Write(byteArray, 0, byteArray.Length); HttpWebResponse response = (HttpWebResponse)webReq.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string ret = string.Empty;//接受返回的json数据 ret = sr.ReadToEnd(); newStream.Close(); response.Close();
get
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postURL); request.ContentType = "application/json"; request.Method = "get"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream instream = response.GetResponseStream(); StreamReader sr = new StreamReader(instream); ret = sr.ReadToEnd(); sr.Close(); response.Close(); instream.Close();