C#——HTTP请求

1、Get请求

使用HttpWebRequest进行Get请求:

public static string get(string url)
{
    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
    StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
    string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
    reader.Close();
    myResponse.Close();
    return returnXml;
}

使用HttpClient进行异步Get请求:

public static string GetData(string url,string data)
{
    string strResult = "";
    try
    {
        url = url+ "?" + data;

        HttpClient httpClient = new HttpClient();
        HttpResponseMessage response = httpClient.GetAsync(url).Result;

        if (response.IsSuccessStatusCode)
        {
            strResult = response.Content.ReadAsStringAsync().Result;
        }
    }
    catch (Exception)
    {

        throw;
    }

    return strResult;
}

2、Post请求

使用HttpClient 进行异步的Post请求:

/// 
/// 接口调用
/// 
/// 
/// 
/// 
public static string PostData(string url, string data)
{
    string strResult = "";
    try
    {
        var str = JsonConvert.SerializeObject(data);
        var httpContent = new StringContent(str, Encoding.UTF8, "application/json");

        //string url = GetConfigUrl(encode);

        HttpClient httpClient = new HttpClient();
        HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

        if (response.IsSuccessStatusCode)
        {
            strResult = response.Content.ReadAsStringAsync().Result;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return strResult;
}

 使用System.Net.HttpWebRequest的Post请求:

public static string sendPost(string url, string postData)
{
    System.Net.HttpWebRequest webrequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
    webrequest.Method = "post";
    webrequest.ContentType = "application/json";
    byte[] postdatabyte = Encoding.UTF8.GetBytes(postData);
    webrequest.ContentLength = postdatabyte.Length;
    Stream stream;
    stream = webrequest.GetRequestStream();
    stream.Write(postdatabyte, 0, postdatabyte.Length);
    stream.Close();
    using (var httpWebResponse = webrequest.GetResponse())
    using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
    {
        String ret = responseStream.ReadToEnd();
        string result = ret.ToString();
        return result;
    }
}

3、使用HttpWebRequest的Cookie的跨登录请求

登录获取Cookie:

CookieContainer globeCookie = new CookieContainer();

public static string DoPostLogin(string url, string data, ref CookieContainer myCookieContainer)
{
    try
    {
        HttpWebRequest webRequest = GetWebRequest(url, "POST");
        webRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
        webRequest.CookieContainer = myCookieContainer;
        byte[] bytes = Encoding.UTF8.GetBytes(data);
        Stream requestStream = webRequest.GetRequestStream();
        requestStream.Write(bytes, 0, bytes.Length);
        requestStream.Close();
        HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
        myCookieContainer.Add(httpWebResponse.Cookies);
        Encoding encoding = Encoding.GetEncoding(httpWebResponse.CharacterSet);
        return GetResponseAsString(httpWebResponse, encoding);
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

使用登录取到的Cookie去访问接口:

public static string DoPost(string url, string data, CookieContainer inputCookieContainer)
{
    try
    {
        HttpWebRequest webRequest = GetWebRequest(url, "POST");
        webRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
        webRequest.CookieContainer = inputCookieContainer;
        byte[] bytes = Encoding.UTF8.GetBytes(data);
        Stream requestStream = webRequest.GetRequestStream();
        requestStream.Write(bytes, 0, bytes.Length);
        requestStream.Close();
        HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
        Encoding encoding = Encoding.GetEncoding(httpWebResponse.CharacterSet);
        return GetResponseAsString(httpWebResponse, encoding);
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

4、请求form表单

public static string PostDS(string url, string data, string ticket)
        {
            string result = "";
            try
            {
                string SendMessageAddress = url;//请求链接
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SendMessageAddress);
                request.Method = "POST";
                request.AllowAutoRedirect = true;
                //request.Timeout = 20 * 1000;
                request.ContentType = "application/x-www-form-urlencoded";
                request.Headers.Add("Authorization", ticket);
                //string PostData = "a=1&b=2";//请求参数格式
                string PostData = data;//请求参数
                byte[] byteArray = Encoding.Default.GetBytes(PostData);
                request.ContentLength = byteArray.Length;
                using (Stream newStream = request.GetRequestStream())
                {
                    newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                    newStream.Close();
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream rspStream = response.GetResponseStream();
                using (StreamReader reader = new StreamReader(rspStream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                    rspStream.Close();
                }
                response.Close();
            }
            catch (Exception ex)
            {
                result = "false";
            }
            return result;
        }

你可能感兴趣的:(c#,http)