HTTP的post和get总结
贴一下自己的源码
post:
string postData = "username=" + username + "&password=" + password;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://192.168.1.8:8080/TrunkBeans/RpcService");
//HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 300000;
Encoding encoding = Encoding.GetEncoding("gb2312");//处理中文乱码
byte[] bytes = encoding.GetBytes(postData);
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Flush();
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gb2312"));
string responseString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
MessageBox.Show(responseString);
get:
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.google.com/webhp?hl=zh-CN" );
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
post上传文件
private void addpic_Click(object sender, EventArgs e)
{
this.openPic.Filter = "图片文件(*.jpg,*.gif,*.bmp)|*.jpg|*.gif|*.bmp";
if(DialogResult.OK==this.openPic.ShowDialog()&&(this.openPic.FileName!=null))
{
Bitmap bit = new Bitmap(this.openPic.FileName);
this.pictureBox1.Image = Image.FromHbitmap(bit.GetHbitmap());
int last = this.openPic.FileName.LastIndexOf(".");
string dat = this.openPic.FileName.Substring(last);
DateTime date = DateTime.Now;
picname=date.ToString("yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
picname = picname + dat;
//MessageBox.Show(picpath + @"/" + picname + ".png");
//File.Move(this.openPic.FileName,picpath+@"/"+picname);
File.Copy(this.openPic.FileName, picpath + @"/" + picname);
string urlStr = "http://192.168.1.45:8080/news/HelloPostFile.jsp";
UploadFileBinary1(picpath + "//"+picname, urlStr);
}
}
public void UploadFileBinary1(string localFile, string uploadUrl)
{
try
{
DateTime time1;
time1 = DateTime.Now;
long num3 = time1.Ticks;
//text1 = "---------------------" + num3.ToString("x");
string boundary = "---------------------------" + num3.ToString("x");
// Build up the post message header
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(boundary);
sb.Append("/r/n");
sb.Append("Content-Disposition: form-data; name=/"file/"; filename=/"");
sb.Append(localFile);
sb.Append("/"");
sb.Append("/r/n");
sb.Append("Content-Type: application/octet-stream");
// sb.Append("Content-Type: application/x-xml");
//sb.Append("Content-Type: text/xml");
sb.Append("/r/n");
sb.Append("/r/n");
string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
byte[] boundaryBytes = Encoding.ASCII.GetBytes("/r/n--" + boundary + "/r/n");
// Open the local file
FileStream rdr = new FileStream(localFile, FileMode.Open);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);
req.Method = "post";
req.AllowWriteStreamBuffering = true;
req.ContentType = "multipart/form-data boundary=" + boundary;
//req.ContentLength == boundaryBytes.Length + postHeaderBytes.Length + rdr.Length;
req.ContentLength = boundaryBytes.Length + postHeaderBytes.Length + rdr.Length;
// Retrieve request stream
Stream reqStream = req.GetRequestStream();
// BinaryReader r = new BinaryReader(rdr);
// byte[] postArray = r.ReadBytes((int)fs.Length);
// Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
reqStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// Allocate byte buffer to hold file contents
long length = rdr.Length;
byte[] inData = new byte[409600];
// loop through the local file reading each data block
// and writing to the request stream buffer
int bytesRead = rdr.Read(inData, 0, inData.Length);
while (bytesRead > 0)
{
reqStream.Write(inData, 0, bytesRead);
bytesRead = rdr.Read(inData, 0, inData.Length);
}
rdr.Close();
reqStream.Write(boundaryBytes, 0, boundaryBytes.Length);
reqStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gb2312"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
// response.Close();
}
catch (Exception ex)
{
string exContent;
exContent = ex.ToString();
MessageBox.Show(exContent);
}
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";//这无论是赋post还是get,都必须用全大写,此值错一点,都会导致程序错误,因为不符合http协议
request.ContentType = "multipart/form-data; boundary=--abc";//或者为"application/x-www-form-urlencoded",对应form标签里的 enctype属性,boundary那部分查是FORM元素各值的分隔符,具体请查阅HTTP协议相关文档,如果此值用application/x- www-form-urlencoded则form各元素用&来分隔,而元素的值是经过了url编码,调用System.Web.HttpUtility.UrlEncode方法,就能将值进行url编码。
//如果需要加cookie,则按如下方式添加,具体请参阅msdn
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(new Cookie("test", "i love u", "/", "localhost"));
byte[] data = Encoding.GetEncoding(encoding).GetBytes(postData);//将要发送的数据按HTTP协议拼装好字符串转成字节数组
request.ContentLength = data.Length;//设置内容的长度,长度就是要发送的整个字节数组的长度,此句必须有,长度不对就会导致错误
request.GetRequestStream().Write(data, 0, data.Length);//获取request的流,将数据写入流中,至此完成了form提交的必须有的步骤
response = (HttpWebResponse)request.GetResponse();//最后取得response获取服务器端的返回数据进行处理