asp.net后台发送HTTP请求
一、文件流方式(转自:http://blog.csdn.net/u011511086/article/details/53216330)
/// 发送请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="sendData">参数格式 “name=王武&pass=123456”</param>
/// <returns></returns>
public static string RequestWebAPI(string url, string sendData)
{
string backMsg = "";
try
{
System.Net.WebRequest httpRquest = System.Net.HttpWebRequest.Create(url);
httpRquest.Method = "POST";
//这行代码很关键,不设置ContentType将导致后台参数获取不到值
httpRquest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
//httpRquest.ContentLength = dataArray.Length;
System.IO.Stream requestStream = null;
if (string.IsNullOrWhiteSpace(sendData) == false)
{
requestStream = httpRquest.GetRequestStream();
requestStream.Write(dataArray, , dataArray.Length);
requestStream.Close();
}
System.Net.WebResponse response = httpRquest.GetResponse();
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
backMsg = reader.ReadToEnd(); reader.Close();
reader.Dispose(); requestStream.Dispose();
responseStream.Close();
responseStream.Dispose();
}
catch (Exception)
{
throw;
}
return backMsg;
}
二、HttpClient方式(转自:http://blog.csdn.net/qianmenfei/article/details/37974767)
1、通用http类
using System;
using System.Globalization;
using System.Net;
using System.Text; namespace Test
{
public class HttpCommon
{
/// <summary>
/// Http同步Get同步请求
/// </summary>
/// <param name="url">Url地址</param>
/// <param name="encode">编码(默认UTF8)</param>
/// <returns></returns>
public static string HttpGet(string url, Encoding encode = null)
{
string result; try
{
var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null)
webClient.Encoding = encode; result = webClient.DownloadString(url);
}
catch (Exception ex)
{
result = ex.Message;
} return result;
} /// <summary>
/// Http同步Get异步请求
/// </summary>
/// <param name="url">Url地址</param>
/// <param name="callBackDownStringCompleted">回调事件</param>
/// <param name="encode">编码(默认UTF8)</param>
public static void HttpGetAsync(string url,
DownloadStringCompletedEventHandler callBackDownStringCompleted = null, Encoding encode = null)
{
var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null)
webClient.Encoding = encode; if (callBackDownStringCompleted != null)
webClient.DownloadStringCompleted += callBackDownStringCompleted; webClient.DownloadStringAsync(new Uri(url));
} /// <summary>
/// Http同步Post同步请求
/// </summary>
/// <param name="url">Url地址</param>
/// <param name="postStr">请求Url数据</param>
/// <param name="encode">编码(默认UTF8)</param>
/// <returns></returns>
public static string HttpPost(string url, string postStr = "", Encoding encode = null)
{
string result; try
{
var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null)
webClient.Encoding = encode; var sendData = Encoding.GetEncoding("GB2312").GetBytes(postStr); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
webClient.Headers.Add("ContentLength", sendData.Length.ToString(CultureInfo.InvariantCulture)); var readData = webClient.UploadData(url, "POST", sendData); result = Encoding.GetEncoding("GB2312").GetString(readData); }
catch (Exception ex)
{
result = ex.Message;
} return result;
} /// <summary>
/// Http同步Post异步请求
/// </summary>
/// <param name="url">Url地址</param>
/// <param name="postStr">请求Url数据</param>
/// <param name="callBackUploadDataCompleted">回调事件</param>
/// <param name="encode"></param>
public static void HttpPostAsync(string url, string postStr = "",
UploadDataCompletedEventHandler callBackUploadDataCompleted = null, Encoding encode = null)
{
var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null)
webClient.Encoding = encode; var sendData = Encoding.GetEncoding("GB2312").GetBytes(postStr); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
webClient.Headers.Add("ContentLength", sendData.Length.ToString(CultureInfo.InvariantCulture)); if (callBackUploadDataCompleted != null)
webClient.UploadDataCompleted += callBackUploadDataCompleted; webClient.UploadDataAsync(new Uri(url), "POST", sendData);
}
}
}
2、调用类
using System;
using System.Net;
using System.Text;
using System.Web.UI; namespace Test
{
public partial class WebForm3 : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(HttpCommon.HttpGet("http://localhost:14954/WebForm4.aspx")); //Get同步
HttpCommon.HttpGetAsync("http://localhost:14954/WebForm4.aspx"); //Get异步
HttpCommon.HttpGetAsync("http://localhost:14954/WebForm4.aspx", DownStringCompleted); //Get异步回调 Response.Write(HttpCommon.HttpPost("http://localhost:14954/WebForm4.aspx", "post=POST")); //Post同步
HttpCommon.HttpPostAsync("http://localhost:14954/WebForm4.aspx", "post=POST"); //Post异步
HttpCommon.HttpPostAsync("http://localhost:14954/WebForm4.aspx", "post=POST", UploadDataCompleted); //Post异步回调
} private void DownStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Response.Write(e.Result);
} private void UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
Response.Write(Encoding.GetEncoding("GB2312").GetString(e.Result));
}
}
}
asp.net后台发送HTTP请求的更多相关文章
- 腾讯云图片鉴黄集成到C# SQL Server 怎么在分页获取数据的同时获取到总记录数 sqlserver 操作数据表语句模板 .NET MVC后台发送post请求 百度api查询多个地址的经纬度的问题 try{}里有一个 return 语句,那么紧跟在这个 try 后的 finally {}里的 code 会 不会被执行,什么时候被执行,在 return 前还是后? js获取某个日期
腾讯云图片鉴黄集成到C# 官方文档:https://cloud.tencent.com/document/product/641/12422 请求官方API及签名的生成代码如下: public c ...
- 后台发送http请求通用方法,包括get和post
package com.examsafety.service.sh; import java.io.BufferedReader; import java.io.IOException; import ...
- C#后台发送HTTP请求
using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using Syst ...
- 后台发送get请求
第一步:编写Controller,让后台去请求接口 package controller; import java.util.List; import org.springframework.bean ...
- Django(十二)视图--利用jquery从后台发送ajax请求并处理、ajax登录案例
一.Ajax基本概念 [参考]:https://www.runoob.com/jquery/jquery-ajax-intro.html 异步的javascript.在不全部加载某一个页面部的情况下, ...
- 理解ASP.NET Core - 发送Http请求(HttpClient)
注:本文隶属于<理解ASP.NET Core>系列文章,请查看置顶博客或点击此处查看全文目录 前言 在.NET中,我们有很多发送Http请求的手段,如HttpWebRequest.WebC ...
- .NET MVC后台发送post请求
一.WebRequest方式 //设置请求接口 var request = (HttpWebRequest)WebRequest.Create("http://xxx.com/xxx&quo ...
- asp.net 后台 Http POST请求
时间忙,简单些,直接贴代码上图 百度站长平台为站长提供链接提交通道,您可以提交想被百度收录的链接,百度搜索引擎会按照标准处理 http://zhanzhang.baidu.com/linksubmit ...
- C# 后台发送get,post请求及WebApi接收
后台发送get请求 1.发送带参数的get请求 /// <summary> /// 发送get请求 参数拼接在url后面 /// </summary> /// <para ...
随机推荐
- 6656 Watching the Kangaroo
6656 Watching the KangarooDay by day number of Kangaroos is decreasing just liketiger, whale or lion ...
- 最长上升子序列 LIS(Longest Increasing Subsequence)
引出: 问题描述:给出一个序列a1,a2,a3,a4,a5,a6,a7….an,求它的一个子序列(设为s1,s2,…sn),使得这个子序列满足这样的性质,s1<s2<s3<…< ...
- ubuntu系统如何屏幕截图
我们知道,windows下有很多截图的软件和插件,那么在ubuntu系统下我们该怎样截图呢? 下面就让小编来告诉你几种简单的方法吧. 工具/原料 ubuntu系统电脑 方法一: 1.也许很多朋友都知道 ...
- MVC中Controller控制器相关技术
第6章Controller相关技术 Controller(控制器)在ASP.NET MVC中负责控制所有客户端与服务器端的交互,并 且负责协调Model与View之间的数椐传递,是ASP.NET MV ...
- epoll模型的使用
1. 创建epoll句柄 int epfd = epoll_create(int size); 该函数生成一个epoll专用的文件描述符.它其实是在内核申请一空间,用来存放你想关注的socket fd ...
- ItemsPanelTemplate的用法
项目里想用Silverlight制作工具栏,之前用的是Image和TextBlock完成的,但是代码混乱,在后来版本中突然想到ListBox可以实现这样的效果.使用后效果确实不错.下面是我的笔记 &l ...
- 从实践的角度理解cookie的几个属性
cookie的处理流程大致分为以下几步: 1.浏览器初次请求服务器. 2.服务器认为有必要设置cookie,通过响应报文首部:Set-Cookie告知浏览器,cookie的内容. 3.浏览器本地保存( ...
- ABAP 选择屏幕创建标签页
*&---------------------------------------------------------------------* *& Report ZTEST_TAB ...
- HTML5之indexedDB
从陌生到了解,花了一下午的时间,以下的地址还是不错的参考资料,省的到处去找 HTML5本地存储——IndexedDB(一:基本使用) 官方API接口文档 官方使用示例 html5 初试 indexed ...
- centos安装SWFtools服务(pdf2swf)
第一步:下载swftools-0.9.2.tar.gz 第二步:swftools tar -xzvf swftools-0.9.2.tar.gz cd swftools-0.9.2 ./configu ...