URL的post

本文介绍了一个使用ASP.NET向指定URL发送POST请求的具体实现方式,并展示了如何解析响应内容及在另一端接收这些POST数据的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

///////post页面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Net;
public partial class urlpost : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string test = RequestPost("5", "http://localhost:1303/txweb/getURL.aspx", "");
        }
    }

    #region  向Url发送post请求,返回网站响应内容
    /// <summary>
    /// 向Url发送post请求,返回网站响应内容
    /// </summary>
    /// <param name="postData">发送数据</param>
    /// <param name="uriStr">接受数据的Url</param>
    /// <param name="action">更新操作</param>
    /// <returns>返回网站响应内容</returns>
    public static string RequestPost(string postData, string uriStr, string action)
    {
        HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create(uriStr);
        StringBuilder postContent = new StringBuilder();
        Encoding myEncoding = Encoding.GetEncoding("gb2312");
        postContent.Append(HttpUtility.UrlEncode("message", myEncoding));
        postContent.Append("=");
        postContent.Append(HttpUtility.UrlEncode(postData, myEncoding));
        //postContent.Append("&");
        //postContent.Append(HttpUtility.UrlEncode("type", myEncoding));
        //postContent.Append("=");
        //postContent.Append(HttpUtility.UrlEncode("sync", myEncoding));
        //postContent.Append("&");
        //postContent.Append(HttpUtility.UrlEncode("action", myEncoding));
        //postContent.Append("=");
        //postContent.Append(HttpUtility.UrlEncode(action, myEncoding));


          requestScore.Headers.Add("qb_count", QB);    //header传参 重要

        byte[] data = Encoding.ASCII.GetBytes(postContent.ToString());
        requestScore.Method = "Post";
        requestScore.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
        requestScore.ContentLength = data.Length;
        requestScore.KeepAlive = true;
        Stream stream = requestScore.GetRequestStream();
        stream.Write(data, 0, data.Length);
        stream.Close();
        HttpWebResponse responseSorce;
        try
        {
            responseSorce = (HttpWebResponse)requestScore.GetResponse();
        }
        catch (WebException ex)
        {
            responseSorce = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示
        }
        StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.UTF8);
        string content = reader.ReadToEnd();
        requestScore.Abort();
        responseSorce.Close();
        responseSorce.Close();
        reader.Dispose();
        stream.Dispose();
        return content;
    }

    #endregion

}

 

/////get页面 网站接收数据:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class getURL : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string message = Request.Form["message"];     
           

        }
    }
}

 

 

////////不带参数的body接收

 if (!IsPostBack)
        {
     
                System.IO.Stream sm = Request.InputStream;//获取post正文
                int len = (int)sm.Length;//post数据长度
                byte[] inputByts = new byte[len];//字节数据,用于存储post数据
                sm.Read(inputByts, 0, len);//将post数据写入byte数组中
                sm.Close();//关闭IO流

                //**********下面是把字节数组类型转换成字符串**********
                string data = System.Text.Encoding.GetEncoding("utf-8").GetString(inputByts);//转为unicode编码
                data = Server.UrlDecode(data);//下面解释一下Server.UrlDecode和Server.UrlEncode的作用
          

            ////////数据解密
                string srt = Des3Encode.Des3.strOutCODE(data);
        }

 

 


          /// <summary>
          /// 以GET 形式获取数据
          /// </summary>
          /// <param name="RequestPara"></param>
          /// <param name="Url"></param>
          /// <returns></returns>
 
        public static  string GetData(string RequestPara, string Url)
          {
              RequestPara=RequestPara.IndexOf('?')>-1?(RequestPara):("?"+RequestPara);
 
              WebRequest hr = HttpWebRequest.Create(Url + RequestPara);
 
              byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);         
             hr.Method = "GET";
 
              System.Net.WebResponse response = hr.GetResponse();
              StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
              string ReturnVal = reader.ReadToEnd();
              reader.Close();
              response.Close();
 
              return ReturnVal;
          }
 

 

 

 

### 如何使用 URL 发送 POST 请求 #### Java 实现方式 为了利用Java发送POST请求,可以采用`HttpURLConnection`类来实现网络通信功能。下面是一个简单的例子,在此案例里,先构建目标服务器地址的URL对象;随后初始化连接并指定HTTP动作为POST模式。 ```java import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class PostExample { public static void main(String[] args) throws Exception { String targetUrl = "http://example.com/api"; URL url = new URL(targetUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置必要的属性 connection.setRequestMethod("POST"); connection.setDoOutput(true); // 启用输出流 try(OutputStream os = connection.getOutputStream()) { String postData = "param1=value1&param2=value2"; os.write(postData.getBytes()); os.flush(); } int responseCode = connection.getResponseCode(); System.out.println("Response Code : " + responseCode); } } ``` #### Python 实现方式 Python 中最常用的是 `requests` 库来进行 HTTP 请求操作。这里展示一段向特定网址提交键值对数据的例子: ```python import requests url = 'http://httpbin.org/post' payload = {'key1': 'value1', 'key2': 'value2'} response = requests.post(url, data=payload) print(response.text) ``` 这段脚本会把 payload 字典里的内容按照 form 表单的方式编码成 application/x-www-form-urlencoded 类型,并将其附加到 POST 请求体内一并发往指定位置[^2]。 #### JavaScript 实现方式 对于前端开发而言,可以通过JavaScript发起异步请求。如果想要模拟表单提交行为,则可借助于XMLHttpRequest 或者 Fetch API 来完成这项工作。以下是基于Fetch API 的解决方案之一: ```javascript fetch('https://api.example.com/submit', { method: 'POST', headers: { 'Content-Type': 'application/json;charset=utf-8' }, body: JSON.stringify({ key1: 'value1', key2: 'value2' }) }) .then((res) => res.json()) .then((result) => console.log(result)) .catch((err) => console.error(err)); ``` 以上三种编程语言都展示了如何通过设定不同的参数选项以及配置项去构造一个完整的POST请求过程[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值