C#访问url地址并返回数据

时间:2024-03-26 19:06:26
  public partial class Form1 : Form
{
static bool isSelect = false;
public Form1()
{
InitializeComponent();
textBox3.Enabled = textBox1.Enabled = false;
} private void button1_Click(object sender, EventArgs e)
{
if (isSelect == false)
{
textBox2.Text = GetResponseData(textBox1.Text.Trim().Replace("\n", "").Replace("\r", ""), textBox3.Text.Trim().Replace("\r", "").Replace("\n", ""));
}
else
{
textBox2.Text = HttpGet(textBox1.Text.Trim().Replace("\n", "").Replace("\r", ""));
} //textBox2.Text = HttpGet(textBox1.Text.Trim());
} public string HttpGet(string Url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close(); return retString;
} public string GetResponseData(string JSONData, string Url)
{
byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentLength = bytes.Length;
request.ContentType = "text/xml";
Stream reqstream = request.GetRequestStream();
reqstream.Write(bytes, , bytes.Length); //声明一个HttpWebRequest请求
request.Timeout = ;
//设置连接超时时间
request.Headers.Set("Pragma", "no-cache");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
Encoding encoding = Encoding.UTF8; StreamReader streamReader = new StreamReader(streamReceive, encoding);
string strResult = streamReader.ReadToEnd();
streamReceive.Dispose();
streamReader.Dispose(); return strResult;
} private void label2_Click(object sender, EventArgs e)
{ } private void radioButton1_Click(object sender, EventArgs e)
{
isSelect = true;
label1.Text = "url";
textBox1.Enabled = true;
textBox3.Enabled = false;
} private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
isSelect = false;
label1.Text = "json";
textBox3.Enabled = textBox1.Enabled = true;
}
}