简体   繁体   中英

How to send large post string data via WebRequest?

I'm sending the content of the file via post request using WebRequest.

It is working fine when the file has less content but it is not sending any data when the content is large.

WebRequest HttpWebRequest = WebRequest.Create("http://testapi.com");

HttpWebRequest.Method = "POST";
HttpWebRequest.Headers.Add("X-API-KEY", APIKEY);

byte[] data = Encoding.UTF8.GetBytes(postdata);

HttpWebRequest.ContentType = "application/x-www-form-urlencoded";
HttpWebRequest.ContentLength = data.Length;

Stream requestStream = HttpWebRequest.GetRequestStream();  

requestStream.Write(data, 0, data.Length);
requestStream.Close();

I'm getting the empty array at the API end. It should get all the file content that I'm sending.

I tried with postman and it worked fine. So I think the issue is in c# side.

You have a big file, first of all you have to encode it:

StringBuilder fileContents = new StringBuilder();
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(@"c:\test.txt");
while((line = file.ReadLine()) != null)
{
fileContents.Append( WebUtility.UrlEncod(line)+ '%0A');
}

file.Close();

after that

         Uri uri = new Uri("http://testapi.com");
         using(WebClient myWebClient = new WebClient())
         {
           myWebClient.Headers.Add("X-API-KEY",APIKEY);
           myWebClient.Headers.Add("Content-Type","application/x-www-form- urlencoded");

           string result = myWebClient.UploadString(uri ,"plu_str="+fileContents.ToString());
          }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM