c# http get請求與post請求實例


//http請求工具類

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace HttpTest
{
class HttpUtil
{

/// <summary>
/// get請求
/// </summary>
/// <param name="url">網絡地址</param>
/// <param name="parm">參數</param>
/// <returns></returns>
public static string HttpGet(string url,string parm){

return HttpRequest(url,parm,"GET");

}

/// <summary>
/// post請求
/// </summary>
/// <param name="url">網絡地址</param>
/// <param name="parm">參數</param>
/// <returns></returns>
public static string HttpPost(string url,string parm) {

return HttpRequest(url,parm,"POST");
}

 

/// <summary>
/// 網絡請求
/// </summary>
/// <param name="url">網絡地址</param>
/// <param name="parm">參數</param>
/// <param name="method">請求方式</param>
/// <returns></returns>
private static string HttpRequest(string url, string parm, string method)
{

if(method.Equals("GET")){

url = url + "?" + parm;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.Timeout = 5 * 1000;
request.AllowWriteStreamBuffering = true;
request.AllowWriteStreamBuffering = true;
request.ContentType = "text/html;charset=UTF-8";
// request.ContentType = "application/x-www-form-urlencoded";
if (method.Equals("POST"))
{
StreamWriter wr = new StreamWriter(request.GetRequestStream(), Encoding.UTF8);
wr.Write(parm);
wr.Flush();
wr.Close();
}

HttpWebResponse respone = (HttpWebResponse)request.GetResponse();
var stream = respone.GetResponseStream();
StreamReader red = new StreamReader(stream, Encoding.UTF8);
string str = red.ReadToEnd();
red.Close();
stream.Flush();
stream.Close();
return str;
}
}
}

//調用示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HttpTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(HttpUtil.HttpGet("https://hao.360.cn/?s0001",""));
}
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM