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获取服务器端的返回数据进行处理




     本文转自xyz_lmn51CTO博客,原文链接:http://blog.51cto.com/xyzlmn/819087,如需转载请自行联系原作者


相关文章
|
4月前
|
Android开发 Kotlin
|
4月前
HTTP协议中请求方式GET 与 POST 什么区别 ?
GET和POST的主要区别在于参数传递方式、安全性和应用场景。GET通过URL传递参数,长度受限且安全性较低,适合获取数据;而POST通过请求体传递参数,安全性更高,适合提交数据。
556 2
|
9月前
|
API 开发者
了解 HTTP 的PUT 与 POST方法的综合指南
HTTP PUT 和 POST 方法是构建 Web 应用与 API 的核心工具,用于资源的创建与更新。PUT 方法通过指定 URL 更新或创建完整资源,具有幂等性;而 POST 方法更灵活,主要用于创建新资源,但不具备幂等性。本文详细对比了两者在请求体、URL 使用、资源处理等方面的区别,并提供了实际应用示例,帮助开发者根据场景选择合适的方法以优化 API 设计。
|
9月前
|
缓存 安全 API
为什么 HTTP GET 方法不使用请求体?
本指南深入探讨了为什么HTTP GET方法通常不使用请求体,解释了GET方法的主要用途及其设计原则。GET请求旨在通过URL安全、幂等地检索数据,避免因请求体带来的复杂性和潜在问题。尽管HTTP/1.1规范允许GET请求包含请求体,但这并不常见且可能引发副作用。掌握这些原则有助于开发者在API开发中更高效地使用GET请求。
|
9月前
|
API
掌握 HTTP 请求的艺术:理解 cURL GET 语法
掌握 cURL GET 请求的语法和使用方法是 Web 开发和测试中的基本技能。通过灵活运用 cURL 提供的各种选项,可以高效地与 API 进行交互、调试网络请求,并自动化日常任务。希望本文能帮助读者更好地理解和使用 cURL,提高工作效率和代码质量。
708 7
|
11月前
|
关系型数据库 MySQL Docker
docker pull mysql:8.0.26提示Error response from daemon: Get “https://registry-1.docker.io/v2/“: EOF错误
docker pull mysql:8.0.26提示Error response from daemon: Get “https://registry-1.docker.io/v2/“: EOF错误
3783 9
|
前端开发 JavaScript Java
如何捕获和处理HTTP GET请求的异常
如何捕获和处理HTTP GET请求的异常
|
存储 缓存 网络协议
计算机网络常见面试题(二):浏览器中输入URL返回页面过程、HTTP协议特点,GET、POST的区别,Cookie与Session
计算机网络常见面试题(二):浏览器中输入URL返回页面过程、HTTP协议特点、状态码、报文格式,GET、POST的区别,DNS的解析过程、数字证书、Cookie与Session,对称加密和非对称加密
|
缓存 安全 API
http 的 get 和 post 区别 1000字
【10月更文挑战第27天】GET和POST方法各有特点,在实际应用中需要根据具体的业务需求和场景选择合适的请求方法,以确保数据的安全传输和正确处理。