使用C#控制台应用程序创建HTTPpost请求并接收响应我需要post数据到URL(https://somesite.com)下载responseStrem中的文件。我如何使用C#控制台应用程序执行此操作?参数:文件名、用户ID、密码、类型看一下System.Net.WebClient类,它可用于发出请求并处理其响应,以及下载文件:http://www.hanselman.com/blog/HTTPPOSTsAndHTTPGETsWithWebClientAndCAndFakingAPostBack.aspxhttp://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx使用系统;使用System.Collections.Generic;使用System.Linq;使用系统文本;使用系统。网;使用System.IO;namespaceWebserverInteractionClassLibrary{publicclassRequestManager{publicstringLastResponse{protectedset;得到;}CookieContainercookies=newCookieContainer();内部字符串GetCookieValue(UriSiteUri,字符串名称){Cookiecookie=cookies.GetCookies(SiteUri)[名称];返回(cookie==null)?null:cookie.Value;}publicstringGetResponseContent(HttpWebResponseresponse){if(response==null){thrownewArgumentNullException("response");}流数据流=null;StreamReader阅读器=null;字符串responseFromServer=null;尝试{//获取包含服务器返回内容的流。dataStream=response.GetResponseStream();//使用StreamReader打开流以便于访问。reader=newStreamReader(dataStream);//读取内容。responseFromServer=reader.ReadToEnd();//清理流和响应。}catch(Exceptionex){Console.WriteLine(ex.Message);}finally{if(reader!=null){reader.Close();}if(dataStream!=null){dataStream.Close();}response.Close();}LastResponse=responseFromServer;返回响应来自服务器;}publicHttpWebResponseSendPOSTRequest(stringuri,stringcontent,stringlogin,stringpassword,boolallowAutoRedirect){HttpWebRequestrequest=GeneratePOSTRequest(uri,content,login,password,allowAutoRedirect);返回GetResponse(请求);}publicHttpWebResponseSendGETRequest(stringuri,stringlogin,stringpassword,boolallowAutoRedirect){HttpWebRequestrequest=GenerateGETRequest(uri,login,pas剑,允许自动重定向);返回GetResponse(请求);}publicHttpWebResponseSendRequest(stringuri,stringcontent,stringmethod,stringlogin,stringpassword,boolallowAutoRedirect){HttpWebRequestrequest=GenerateRequest(uri,content,method,login,password,allowAutoRedirect);返回GetResponse(请求);}publicHttpWebRequestGenerateGETRequest(stringuri,stringlogin,stringpassword,boolallowAutoRedirect){returnGenerateRequest(uri,null,"GET",null,null,allowAutoRedirect);}publicHttpWebRequestGeneratePOSTRequest(stringuri,stringcontent,stringlogin,stringpassword,boolallowAutoRedirect){returnGenerateRequest(uri,content,"POST",null,null,allowAutoRedirect);}internalHttpWebRequestGenerateRequest(stringuri,stringcontent,stringmethod,stringlogin,stringpassword,boolallowAutoRedirect){if(uri==null){thrownewArgumentNullException("uri");}//使用可以接收的URL创建请求给一个职位。HttpWebRequest请求=(HttpWebRequest)HttpWebRequest.Create(uri);//将请求的方法属性设置为POST。request.Method=方法;//设置cookie容器来维护cookiesrequest.CookieContainer=cookies;request.AllowAutoRedirect=allowAutoRedirect;//如果登录为空,则使用默认凭证}else{request.Credentials=newNetworkCredential(login,password);}if(method=="POST"){//将POST数据转换为字节数组。byte[]byteArray=Encoding.UTF8.GetBytes(内容);//设置WebRequest的ContentType属性。request.ContentType="application/x-www-form-urlencoded";//设置WebRequest的ContentLength属性。request.ContentLength=byteArray.Length;//获取请求流。流数据流=request.GetRequestStream();//将数据写入请求流。dataStream.Write(byteArray,0,byteArray.Length);//关闭流对象.dataStream.Close();}返回请求;}internalHttpWebResponseGetResponse(HttpWebRequestrequest){if(request==null){thrownewArgumentNullException("request");}HttpWebResponse响应=null;尝试{response=(HttpWebResponse)request.GetResponse();cookies.Add(response.Cookies);//打印每个cookie的属性。Console.WriteLine("nCookies:");foreach(Cookiecookincookies.GetCookies(request.RequestUri)){控制台。WriteLine("域名:{0},字符串:{1}",cook.Domain,cook.ToString());}}catch(WebExceptionex){Console.WriteLine("Web异常发生。状态码:{0}",ex.Status);}catch(Exceptionex){Console.WriteLine(ex.Message);}返回响应;为此,您可以简单地使用.net中的“HttpWebRequest”和“HttpWebResponse”类。下面是我编写的示例控制台应用程序,用于演示这是多么容易。使用系统;使用System.Collections.Generic;使用系统文本;使用System.Net;使用System.IO;namespaceTest{classProgram{staticvoidMain(string[]args){stringurl="www.somewhere.com";stringfileName=@"C:output.file";HttpWebRequest请求=(HttpWebRequest)WebRequest.Create(url);请求超时=5000;尝试{使用(WebResponse响应=(HttpWebResponse)request.GetResponse()){使用(FileStream流=新的FileStream(文件名,FileMode.Create,FileAccess.Write)){byte[]bytes=ReadFully(response.GetResponseStream());stream.Write(bytes,0,bytes.Length);}}}catch(WebException){Console.WriteLine("发生错误");}}publicstaticbyte[]ReadFully(Streaminput){byte[]buffer=newbyte[16*1024];使用(MemoryStreamms=newMemoryStream()){intread;while((read=input.Read(buffer,0,buffer.Length))>0){ms.Write(buffer,0,read);}返回ms.ToArray();}}}}请享用!HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create("someurl");request.Method="POST";request.ContentType="application/x-www-form-urlencoded";request.UserAgent="Mozilla/5.0(compatible;MSIE9.0;WindowsNT7.1;Trident/5.0)";request.Accept="/";request.UseDefaultCredentials=true;request.Proxy.Credentials=System.Net.CredentialCache.DefaultCredentials;doc.Save(request.GetRequestStream());HttpWebResponseresp=request.GetResponse()asHttpWebResponse;我希望它可以帮助你。以上就是C#学习教程:使用C#控制台应用创建HTTPpost请求并接收响应的全部内容分享。如果对大家有用,需要了解更多关于C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:
