简体   繁体   中英

Add a loop to a POST in C#

How can the following code be modified to loop through a text file instead of the static 'testData' string? The first block of code POST works, my attempt to use a loop is the second block of code below, but it's not working.

<%@ Page Language="C#" Debug="true" %>
<%@ Import Namespace="System.Net"%>
<%@ Import Namespace="System.IO"%>
<%
    string url = "http://testurl.com/test";
    HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
    HttpWebResponse response = null;
    string user = "testuser";
    string password = "testpassword";
    string testData ="id=003&email=test@hotmail.com&firstname=Test&lastname=User";
    byte[] byteData = Encoding.UTF8.GetBytes(mydata);
    UTF8Encoding enc = new UTF8Encoding();
    request.Method = "POST";
    string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + password));
    request.PreAuthenticate = true;
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = byteData.Length;
    request.Accept = "application/json";
    request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
    request.Headers.Add("Authorization", auth);
    using (Stream ds = request.GetRequestStream())
    {
        ds.Write(byteData, 0, byteData.Length);
        ds.Close();
    } 
    try
    {
        response = (HttpWebResponse)request.GetResponse();
    } 
    catch (WebException ex)
    {
        response = (HttpWebResponse)ex.Response;
    }
    Stream receiveStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
    string content = reader.ReadToEnd();
    Response.Write(content);
%>

The following does not work, I get the error 'this property cannot be set after writing has started' on the ContentLength line

<%@ Page Language="C#" Debug="true" %>
<%@ Import Namespace="System.Net"%>
<%@ Import Namespace="System.IO"%>
<%
    string url = "http://testurl.com/test";
    HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
    HttpWebResponse wr = null;
    string user = "testuser";
    string pwd = "testpassword";
    string fileName = @"C:\TestDir\Test.txt";
    string[] lines = System.IO.File.ReadAllLines(fileName);
    foreach (string line in lines)
    {
        string mydata = line;
        byte[] byteData = Encoding.UTF8.GetBytes(mydata);
        UTF8Encoding enc = new UTF8Encoding();
        req.Method = "POST";
        string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd));
        req.PreAuthenticate = true;
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = byteData.Length;
        req.Accept = "application/json";
        req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
        req.Headers.Add("Authorization", auth);
        using (Stream ds = req.GetRequestStream())
        {
            ds.Write(byteData, 0, byteData.Length);
            ds.Close();
        } 
        try
        {
            wr = (HttpWebResponse)req.GetResponse();
        }
        catch (WebException ex)
        {
            wr = (HttpWebResponse)ex.Response;
        }
        Stream receiveStream = wr.GetResponseStream();
        StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
        string content = reader.ReadToEnd();
        Response.Write(content);
    }
%>

Move the following two lines to be inside your foreach loop

HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
HttpWebResponse wr = null;

what is happening is that you do one request, and then loop goes again and request has already been used, so when you touch sensitive ContenLength property, request is not in the state where it can be modified. You need to create brand new request, which is what will be accomplished by moving those two lines inside the foreach loop

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