引用
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Text;
帮助类代码
public class HttpHelper
{
public static string HttpApi(string url, string jsonstr, string type)
{
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "text/html,application/xhtml+xml,*/*";
request.ContentType = "application/json";
request.Method = type.ToUpper().ToString();
if (jsonstr != null)
{
byte[] buffer = encoding.GetBytes(jsonstr);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
public static HttpWebResponse HttpApiGetResponse(string url, string jsonstr, string type)
{
Encoding encoding = Encoding.UTF8;
if (!url.StartsWith("http://"))
{
url = "http://" + url;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "text/html,application/xhtml+xml,*/*";
request.ContentType = "application/json";
request.Method = type.ToUpper().ToString();
if (!string.IsNullOrEmpty(jsonstr))
{
byte[] buffer = encoding.GetBytes(jsonstr);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return response;
}
public static string HttpUploadFile(string url, string path)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
string boundary = DateTime.Now.Ticks.ToString("X");
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
int pos = path.LastIndexOf("\\");
string fileName = path.Substring(pos + 1);
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"avatar\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[fs.Length];
fs.Read(bArr, 0, bArr.Length);
fs.Close();
Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(bArr, 0, bArr.Length);
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
postStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
string content = sr.ReadToEnd();
return content;
}
public static string Post(string url, Dictionary<string, string> dic)
{
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
return Post(url, builder.ToString(), "application/x-www-form-urlencoded");
}
public static string Post(string Url, string jsonParas)
{
string strURL = Url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/json";
string paraUrlCoded = jsonParas;
byte[] payload;
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
Stream writer;
try
{
writer = request.GetRequestStream();
}
catch (Exception ex)
{
writer = null;
Console.Write(ex.ToString());
Console.Write("连接服务器失败!");
}
writer.Write(payload, 0, payload.Length);
writer.Close();
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
Stream s = response.GetResponseStream();
StreamReader sRead = new StreamReader(s);
string postContent = sRead.ReadToEnd();
sRead.Close();
return postContent;
}
public static string Post(string url, string postData, string contentType)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = "POST";
request.Timeout = 300000;
byte[] bytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = bytes.Length;
Stream writer = request.GetRequestStream();
writer.Write(bytes, 0, bytes.Length);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
string result = reader.ReadToEnd();
response.Close();
return result;
}
public static string Post(string url, string postData, string userName, string password)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "text/html; charset=UTF-8";
request.Method = "POST";
string usernamePassword = userName + ":" + password;
CredentialCache credentialCache =
new CredentialCache { { new Uri(url), "Basic", new NetworkCredential(userName, password) } };
request.Credentials = credentialCache;
request.Headers.Add("Authorization",
"Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
byte[] bytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = bytes.Length;
Stream writer = request.GetRequestStream();
writer.Write(bytes, 0, bytes.Length);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.ASCII);
string result = reader.ReadToEnd();
response.Close();
return result;
}
}