一、文件流方式(转自: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请求的更多相关文章

  1. 腾讯云图片鉴黄集成到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 ...

  2. 后台发送http请求通用方法,包括get和post

    package com.examsafety.service.sh; import java.io.BufferedReader; import java.io.IOException; import ...

  3. C#后台发送HTTP请求

    using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using Syst ...

  4. 后台发送get请求

    第一步:编写Controller,让后台去请求接口 package controller; import java.util.List; import org.springframework.bean ...

  5. Django(十二)视图--利用jquery从后台发送ajax请求并处理、ajax登录案例

    一.Ajax基本概念 [参考]:https://www.runoob.com/jquery/jquery-ajax-intro.html 异步的javascript.在不全部加载某一个页面部的情况下, ...

  6. 理解ASP.NET Core - 发送Http请求(HttpClient)

    注:本文隶属于<理解ASP.NET Core>系列文章,请查看置顶博客或点击此处查看全文目录 前言 在.NET中,我们有很多发送Http请求的手段,如HttpWebRequest.WebC ...

  7. .NET MVC后台发送post请求

    一.WebRequest方式 //设置请求接口 var request = (HttpWebRequest)WebRequest.Create("http://xxx.com/xxx&quo ...

  8. asp.net 后台 Http POST请求

    时间忙,简单些,直接贴代码上图 百度站长平台为站长提供链接提交通道,您可以提交想被百度收录的链接,百度搜索引擎会按照标准处理 http://zhanzhang.baidu.com/linksubmit ...

  9. C# 后台发送get,post请求及WebApi接收

    后台发送get请求 1.发送带参数的get请求 /// <summary> /// 发送get请求 参数拼接在url后面 /// </summary> /// <para ...

随机推荐

  1. bzoj3713 [PA2014]Iloczyn|暴力(模拟)

    斐波那契数列的定义为:k=0或1时,F[k]=k:k>1时,F[k]=F[k-1]+F[k-2].数列的开头几项为0,1,1,2,3,5,8,13,21,34,55,-你的任务是判断给定的数字能 ...

  2. Android02-控件

    在android studio中,新建一个module时布局文件中就会默认带一个TextView,里面显示着一句话:Hello World !  布局中通常放置的是android控件,下面介绍几个an ...

  3. 基于java的后台截图功能的实现

    Java后台截图功能的实现 背景介绍: 在近期开发的可视化二期项目中的邮件项目中,邮件中的正文中含有图片.该图片的产生是将一些html网页转为图片格式,刚开始考虑使用第三方组件库html2image和 ...

  4. javascript字典数据结构Dictionary实现

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat=&qu ...

  5. jQuery Mobile事件,开发全解+完美注释

    全栈工程师开发手册 (作者:栾鹏) jQuery Mobile事件全解 jQuery Mobile 所有class选项 jQuery Mobile 所有data-*选项 jQuery Mobile事件 ...

  6. scala位压缩与行情转换二进制

    import org.jboss.netty.buffer.{ChannelBuffers, ChannelBuffer} import java.nio.charset.Charset import ...

  7. VS2015智能提示由英文改为中文

    使用 VS2015 时,在 4.0 下智能提示显示中文,在 4.5 下显示英文,对于我这种爱(ying)国(yu)人(tai)士(lan)来说,用起来太不方便了,于 是在 知乎 上找到个好方法如下: ...

  8. PE格式第八讲,TLS表(线程局部存储)

    PE格式第八讲,TLS表(线程局部存储) 作者:IBinary出处:http://www.cnblogs.com/iBinary/版权所有,欢迎保留原文链接进行转载:) 一丶复习线程相关知识 首先讲解 ...

  9. Linux: 查看软件安装路径

    一.        Which 命令 Shell 的which 命令可以找出相关命令是否已经在搜索路径中. 如: [root@localhost ~]# which gcc /usr/bin/gcc ...

  10. 《Unity3D/2D游戏开发从0到1(第二版本)》 书稿完结总结

    前几天,个人著作<Unity3D/2D游戏开发从0到1(第二版)>经过七八个月的技术准备以及近3个月的日夜编写,在十一长假后终于完稿.今天抽出一点时间来,给广大热心小伙伴们汇报一下书籍概况 ...