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 ...
随机推荐
- python --- hashlib模块使用详解
这个模块实现了一个通用的接口来实现多个不同的安全哈希和消息摘要算法.包括FIPS安全散列算法SHA1,SHA224,SHA256,SHA384和SHA512(在FIPS 180-2中定义)以及RSA的 ...
- FPGA与PCI-E
从并行到串行: PCI Express(又称PCIe)是一种高性能.高带宽串行通讯互连标准,取代了基于总线的通信架构,如:PCI.PCI Extended (PCI-X) 以及加速图形端口(AGP). ...
- zoj 2022
分析: 组合数学类型的题目. 正常的话可能会去分解1~N数里面有几个5和2,但是这样的复杂度为O(nlogn). 其实有更巧妙的办法,可以把问题分解成子问题. 可以发现N!末尾的0与1~N中有几个5的 ...
- hdu 4057--Rescue the Rabbit(AC自动机+状压DP)
题目链接 Problem Description Dr. X is a biologist, who likes rabbits very much and can do everything for ...
- 使用微软URLRewriter.dll的url实现任意后缀名重写
<?xml version="1.0"?> <!--先引用URLRewriter.dll,放置于Bin目录--> <configuration> ...
- VS2010 c/c++ 本地化 emscripten 配置
配置环境 1.下载emsdk-1.35.0-full-64bit.exe,有VS2010的话直接安装. 2.安装好之后,打开cmd,# emsdk update # emsdk install lat ...
- cocos2dx - v2.3.3编辑器骨骼动画
接上一节内容:cocos2dx - v2.3.3编辑器简单使用及不同分辨率适配 本节主要Cocos骨骼动画的创建及使用 一.新建 用Cocos Studio工具新建一个状态栏项目.如下图: 当然也可以 ...
- 深入浅出Diffie–Hellman
一.作者 这个密钥交换方法,由惠特菲尔德·迪菲(Bailey Whitfield Diffie).马丁·赫尔曼(Martin Edward Hellman)于1976年发表. 二.说明 它是一种安全协 ...
- PowerApps 经验总结
Label的padding不要设置成0,因为有些字体会超出当前的框架,造成Clip效果 Label的AutoHeight并不会将原来自带的Height删除,所以有的时候空间更新属性出现问题,就会造成显 ...
- 安装阿里Java代码规约插件
概述 2017年10月14日杭州云栖大会,Java代码规约扫描插件全球首发仪式正式启动,规范正式以插件形式公开走向业界,引领Java语言的规范之路.目前,插件已在云效公有云产品中集成,立即体验!(云效 ...