C# httpget post訪問WebAPI

/// <summary>
/// get方式訪問webapi
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string httpGet(string url)
{
try
{
HttpWebRequest MyRequest = (HttpWebRequest)WebRequest.Create(url);
MyRequest.Method = "GET";
MyRequest.Accept = "application/json";
//返回類型可以爲
//1、application/json
//2、text/json
//3、application/xml
//4、text/xml


MyRequest.ContentType = "application/json";
//上傳類型是能爲json

 

string retData = null;//接收返回值
HttpWebResponse MyResponse = (HttpWebResponse)MyRequest.GetResponse();
if (MyResponse.StatusCode == HttpStatusCode.OK)
{
Stream MyNewStream = MyResponse.GetResponseStream();
StreamReader MyStreamReader = new StreamReader(MyNewStream, Encoding.UTF8);
retData = MyStreamReader.ReadToEnd();
MyStreamReader.Close();
}
MyResponse.Close();
return retData;
}
catch (Exception ex)
{
return ex.Message;
}
}

/// <summary>
/// post方式訪問webapi
/// </summary>
/// <param name="url"></param>
/// <param name="postdata"></param>
/// <returns></returns>
public static string httpPost(string url, string postdata)
{
try
{
HttpWebRequest MyRequest = (HttpWebRequest)WebRequest.Create(url);
MyRequest.Method = "POST";
MyRequest.Accept = "application/json";
//返回類型可以爲
//1、application/json
//2、text/json
//3、application/xml
//4、text/xml

MyRequest.ContentType = "application/json";
//上傳類型是能爲json

if (postdata != null)
{
ASCIIEncoding MyEncoding = new ASCIIEncoding();
byte[] MyByte = MyEncoding.GetBytes(postdata);
Stream MyStream = MyRequest.GetRequestStream();
MyStream.Write(MyByte, 0, postdata.Length);
MyStream.Close();
}

string retData = null;//返回值
HttpWebResponse MyResponse = (HttpWebResponse)MyRequest.GetResponse();
if (MyResponse.StatusCode == HttpStatusCode.OK)
{
Stream MyNewStream = MyResponse.GetResponseStream();
StreamReader MyStreamReader = new StreamReader(MyNewStream, Encoding.UTF8);
retData = MyStreamReader.ReadToEnd();
MyStreamReader.Close();
}
MyResponse.Close();
return retData;
}
catch (Exception ex)
{
return ex.Message;
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章