GET
//直接返回字符串
public static string Gets(string url, JObject headers)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "Get";
if (headers != null)
{
IEnumerable<JProperty> properties = headers.Properties();
foreach (JProperty item in properties)
{
req.Headers.Add(item.Name, item.Value.ToString());
}
}
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
// 直接读取文件流
public static string HttpGet(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "Get";
try
{
using (WebResponse wr = req.GetResponse())
{
HttpWebResponse response = wr as HttpWebResponse;
Stream stream = response.GetResponseStream();
//读取到内存
MemoryStream ms = new MemoryStream();
byte[] buffer = new byte[1024];
while (true)
{
int sz = stream.Read(buffer, 0, 1024);
if (sz == 0) break;
ms.Write(buffer, 0, sz);
}
string content = Convert.ToBase64String(ms.ToArray());
return content;
}
}
catch (Exception ex)
{
return null;
}
}
POST
application/json
public static string PostWebRequest(string postUrl, string paramData, int? timeOut)
{
string responseContent = string.Empty;
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
//这里的格式根据自己需求替换
webReq.ContentType = "application/json";
webReq.ContentLength = byteArray.Length;
if(timeOut != null) webReq.Timeout = (int)timeOut;
using (Stream reqStream = webReq.GetRequestStream())
{
reqStream.Write(byteArray, 0, byteArray.Length);//写入参数
//reqStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
{
//在这里对接收到的页面内容进行处理
using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
responseContent = sr.ReadToEnd().ToString();
}
}
}
catch (Exception ex)
{
return ex.Message;
}
return responseContent;
}
application/x-www-form-urlencoded
public static string PostUrlFormUrlencoded(string url, string postData)
{
string result = "";
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
//req.Timeout = 8000;//请求超时时间
byte[] data = Encoding.UTF8.GetBytes(postData);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine("发送请求出错:" + e.Message);
}
return result;
}
multipart/form-data
public static string HttpPost(string url, NameValueCollection kVDatas = null, JObject headers = null,
string method = WebRequestMethods.Http.Post, int timeOut = -1)
{
try
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Timeout = timeOut;
if (headers != null)
{
IEnumerable<JProperty> properties = headers.Properties();
foreach (JProperty item in properties)
{
request.Headers.Add(item.Name, item.Value.ToString());
}
}
CredentialCache credentialCache = new CredentialCache
{
{ new Uri(url), "Basic", new NetworkCredential("member", "secret") }
};
request.Credentials = credentialCache;
request.ServicePoint.Expect100Continue = false;
using (Stream stream = request.GetRequestStream())
{
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
if (kVDatas != null)
{
foreach (string key in kVDatas.Keys)
{
stream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, kVDatas[key]);
byte[] formitembytes = Encoding.GetEncoding("UTF-8").GetBytes(formitem);
stream.Write(formitembytes, 0, formitembytes.Length);
}
}
stream.Write(endbytes, 0, endbytes.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
return stream.ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return e.Message;
}
}
使用text形式发送multipart/form-data请求
JObject signatory = new JObject()
{
{ "content", "test content" }
};
string boundary = "---------------------------" + timeStamp;
StringBuilder inStr = new StringBuilder();
inStr.Append("--" + timeStamp + "\r\n");
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
string formitem = string.Format(formdataTemplate, "dataString", signData["content"]);
inStr.Append(formitem);
inStr.Append("\r\n" + "--" + timeStamp + "\r\n");
formitem = string.Format(formdataTemplate, "signatory", JsonConvert.SerializeObject(signatory));
inStr.Append(formitem);
inStr.Append("\r\n" + "--" + timeStamp + "\r\n");
formitem = string.Format(formdataTemplate, "tenantType", "PERSONAL");
inStr.Append(formitem);
inStr.Append("\r\n" + "--" + timeStamp + "\r\n");
inStr.Append("\r\n" + "--" + timeStamp + "--\r\n");
上传文件
public static string HttpUploadFile(string url, string filePath, string fileName, string paramName, string contentType,
NameValueCollection nameValueCollection)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = CredentialCache.DefaultCredentials;
Stream requestStream = request.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nameValueCollection.Keys)
{
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nameValueCollection[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
requestStream.Write(formitembytes, 0, formitembytes.Length);
}
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
string header = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", paramName, fileName, contentType);
byte[] headerbytes = Encoding.UTF8.GetBytes(header);
requestStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
requestStream.Write(trailer, 0, trailer.Length);
requestStream.Close();
WebResponse webResponse = null;
try
{
webResponse = request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string result = streamReader.ReadToEnd();
return result;
}
catch (Exception ex)
{
if (webResponse != null)
{
webResponse.Close();
webResponse = null;
}
return null;
}
finally
{
request = null;
}
}
标签:string,C#,汇总,req,request,Length,HttpWebRequest,new
From: https://www.cnblogs.com/waou/p/18279622