如何修改以下代碼以循環顯示文本文件而不是靜態'testData'字符串?代碼POST的第一塊工作,我嘗試使用循環是下面的第二塊代碼,但它不起作用。向C#中的POST添加循環#
<%@ 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 protected]&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);
%>
下不能正常工作,我得到了錯誤的的ContentLength線
<%@ 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);
}
%>
我認爲你需要在foreach中提出一個新的請求 – Gus
謝謝,那就是問題所在。 –