WebHttpRequest Post请求

一个小例子,在一般处理程序中调用别处的http协议

  1 using System;
  2 
  3 using System.IO;
  4 
  5 using System.Collections;
  6 
  7 using System.Data;
  8 
  9 using System.Linq;
 10 
 11 using System.Web;
 12 
 13 using System.Web.Services;
 14 
 15 using System.Web.Services.Protocols;
 16 
 17 using System.Xml.Linq;
 18 
 19 using System.Net;
 20 
 21 using System.Text;
 22 
 23  
 24 
 25 namespace WebApplication1
 26 
 27 {
 28 
 29  
 30 
 31     [WebService(Namespace = "http://tempuri.org/")]
 32 
 33     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 34 
 35     public class Handler1 : IHttpHandler
 36 
 37     {
 38 
 39  
 40 
 41         public void ProcessRequest(HttpContext context)
 42 
 43         {
 44 
 45             HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://fanyi.baidu.com/transcontent");
 46 
 47             Encoding encoding = Encoding.UTF8;
 48 
 49             string param = "ie=utf-8&source=txt&query=hello&t=1327829764203&token=8a7dcbacb3ed72cad9f3fb079809a127&from=auto&to=auto";
 50 
 51             //encoding.GetBytes(postData);
 52 
 53             byte[] bs = Encoding.ASCII.GetBytes(param);
 54 
 55             string responseData = String.Empty;            
 56 
 57             req.Method = "POST";
 58 
 59             req.ContentType = "application/x-www-form-urlencoded";
 60 
 61             req.ContentLength = bs.Length;
 62 
 63             using (Stream reqStream = req.GetRequestStream())
 64 
 65             {
 66 
 67                 reqStream.Write(bs, 0, bs.Length);
 68 
 69                 reqStream.Close();
 70 
 71             }
 72 
 73             using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
 74 
 75             {
 76 
 77                 using (StreamReader reader = new StreamReader(response.GetResponseStream(),encoding))
 78 
 79                 {
 80 
 81                     responseData = reader.ReadToEnd().ToString();
 82 
 83                 }
 84 
 85                 context.Response.Write(responseData);
 86 
 87             }
 88 
 89         }
 90 
 91         public bool IsReusable
 92 
 93         {
 94 
 95             get
 96 
 97             {
 98 
 99                 return false;
100 
101             }
102 
103         }
104 
105     }
106 
107 } 
原文地址:https://www.cnblogs.com/ithuo/p/4812791.html