Using .NET to Post a file to Server HttpWebRequest or WebClient

北城以北 提交于 2019-12-01 03:41:12

First, use something like fiddler and inspect the requests and responses to see what differs between curl and System.Net.WebClient.

Also, you can try (although inspecting with the debugging proxy should allow you to pinpoint the difference):

Use the credential cache to set your credentials for basic authentication:

var cc= new CredentialCache();
cc.Add(new Uri(url),
                  "Basic", 
                  new NetworkCredential("USERNAME", "PASSWORD"));
wc.Credentials = cc;

Set a user agent header:

string _UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
wc.Headers.Add(HttpRequestHeader.UserAgent, _UserAgent);

Change the protocol version on the WebRequest:

reqeust.KeepAlive = false;
request.ProtocolVersion=HttpVersion.Version10;

There might be another 2 reasons when a 501 accord.

----------1---------

when the postdate contain some Chinese Chracter or some other character. e.g.

postDate = "type=user&username=计算机学院&password=123&Submit=+登录+"

in order post the right message,you may also add following 2 line;

Request.SendChunked = true;
Request.TransferEncoding = "GB2312";

this also lead to a 501.

in that occasion,you can delete the 2 line,and modify postDate like so.

postDate = "type=user&username=%BC%C6%CB%E3%BB%FA%D1%A7%D4%BA&password=123&Submit=+%C8%B7%C8%CF+"

maybe this is a solution to modify the postDate,however i havn't test yet.

string str = Encoding.GetEncoding("gb2312").GetString(tmpBytes);

----------2---------

if Response.StatusCode == HttpStatusCode.Redirect Redirect is equals to 302. following line is a must:

Request.AllowAutoRedirect = false;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!