Post提交数据到接口或网址 获取返回数据

2016/12/29 15:37
阅读数 137
/// <summary>
    /// POST提交XML文件获取返回数据
    /// </summary>
    /// <param name="url">网址</param>
    /// <param name="strPost">XML数据</param>
    /// <returns></returns>
    private string PostXml(string url, string strPost)
    {
        string result = "";

        StreamWriter myWriter = null;

        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
        objRequest.Method = "POST";
        objRequest.ContentLength = strPost.Length;
        objRequest.ContentType = "text/xml";//提交xml 
        //objRequest.ContentType = "application/x-www-form-urlencoded";//提交表单
        try
        {
            myWriter = new StreamWriter(objRequest.GetRequestStream());
            myWriter.Write(strPost);
        }
        catch (Exception e)
        {
            return e.Message;
        }
        finally
        {
            myWriter.Close();
        }

        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
        using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
        {
            result = sr.ReadToEnd();
            sr.Close();
        }
        return result;
    }

    /// <summary>
    /// Post提交获取返回数据
    /// </summary>
    /// <param name="url">网址</param>
    /// <returns></returns>
    protected string GetWebContent(string url)
    {
        Stream outstream = null;
        Stream instream = null;
        StreamReader sr = null;
        HttpWebResponse response = null;
        HttpWebRequest request = null;
        // 要注意的这是这个编码方式,还有内容的Xml内容的编码方式
        Encoding encoding = Encoding.GetEncoding("UTF-8");
        byte[] data = encoding.GetBytes(url);

        // 准备请求,设置参数
        request = WebRequest.Create(url) as HttpWebRequest;
        request.Method = "POST";
        //request.ContentType = "text/plain";
        request.ContentLength = data.Length;

        outstream = request.GetRequestStream();
        outstream.Write(data, 0, data.Length);
        outstream.Flush();
        outstream.Close();
        //发送请求并获取相应回应数据

        response = request.GetResponse() as HttpWebResponse;
        //直到request.GetResponse()程序才开始向目标网页发送Post请求
        instream = response.GetResponseStream();
        sr = new StreamReader(instream, encoding);
        //返回结果网页(html)代码

        string content = sr.ReadToEnd();
        return content;
    }

#region WebService返回的Xml转换成DataSet
    /// <summary>
    /// WebService返回的Xml转换成DataSet
    /// </summary>
    /// <param name="text">Xml字符</param>
    /// <returns></returns>
    private DataSet GetDataSet(string text)
    {
        try
        {
            XmlTextReader reader = new XmlTextReader(new StringReader(text));
            reader.WhitespaceHandling = WhitespaceHandling.None;
            DataSet ds = new DataSet();
            ds.ReadXml(reader);
            reader.Close();
            ds.Dispose();
            return ds;
        }
        catch
        {
            return null;
        }
    }
    #endregion
#region 后台获取ashx返回的数据
    /// <summary>
    /// 后台获取ashx返回的数据
    /// </summary>
    /// <param name="relativePath">地址</param>
    /// <param name="data">参数</param>
    /// <returns></returns>
    public static string GetRequestJsonString(string relativePath, string data)
    {
        string requestUrl = GetRequestUrl(relativePath, data);

        try
        {
            WebRequest request = WebRequest.Create(requestUrl);
            request.Method = "GET";

            StreamReader jsonStream = new StreamReader(request.GetResponse().GetResponseStream());
            string jsonObject = jsonStream.ReadToEnd();

            return jsonObject;
        }
        catch
        {
            return string.Empty;
        }
    }

    public static string GetRequestUrl(string relativePath, string data)
    {
        string absolutePath = HttpContext.Current.Request.Url.AbsoluteUri;
        string hostNameAndPort = HttpContext.Current.Request.Url.Authority;
        string applicationDir = HttpContext.Current.Request.ApplicationPath;
        StringBuilder sbRequestUrl = new StringBuilder();
        sbRequestUrl.Append(absolutePath.Substring(0, absolutePath.IndexOf(hostNameAndPort)));
        sbRequestUrl.Append(hostNameAndPort);
        sbRequestUrl.Append(applicationDir);
        sbRequestUrl.Append(relativePath);
        if (!string.IsNullOrEmpty(data))
        {
            sbRequestUrl.Append("?");
            sbRequestUrl.Append(data);
        }
        return sbRequestUrl.ToString();
    }
    #endregion
//模拟提交数据给接口,获取返回字符串
    protected void Button1_Click(object sender, EventArgs e)
    {
        System.Net.WebClient client = new WebClient();
        System.Collections.Specialized.NameValueCollection collect = new System.Collections.Specialized.NameValueCollection();
        collect.Add("id", "11111");
        collect.Add("name", "lee");
        Byte[] pageData = client.UploadValues("http://localhost:86/Ajax/Handler2.ashx", collect);
        string pageHtml = Encoding.UTF8.GetString(pageData);
        Response.Write(pageHtml);
    }
<%@ WebHandler Language="C#" Class="Handler2" %>
using System;
using System.Web;

public class Handler2 : IHttpHandler {    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string id = context.Request["id"];
        string name = context.Request["name"];
        string returnStr = string.Empty;
        if (!string.IsNullOrEmpty(id)&& !string.IsNullOrEmpty(name))
        {
            returnStr = "序号" + id + ",姓名" + name;
            context.Response.Write(returnStr);
        }
        context.Response.End();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}
#region 提交Json数据且获取接口返回的数据  
/// <summary>
/// 提交Json数据且获取接口返回的数据
/// </summary>
/// <param name="url">网址</param>
/// <param name="method">Get/Post</param>
/// <param name="postDataStr">提交数据{"name":"zhangsan","pwd":"123456"}</param>
/// <returns></returns>
private string HttpPost(string url, string method, string postDataStr)
{
	HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
	request.Method = method;

	if (!string.IsNullOrWhiteSpace(postDataStr))
	{
		request.ContentType = "application/json";
		byte[] postData = Encoding.UTF8.GetBytes(postDataStr);
		request.ContentLength = postData.Length;
		System.IO.Stream outputStream = request.GetRequestStream();
		outputStream.Write(postData, 0, postData.Length);
		outputStream.Close();
	}

	HttpWebResponse response = (HttpWebResponse)request.GetResponse();
	Stream myResponseStream = response.GetResponseStream();
	StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
	string retString = myStreamReader.ReadToEnd();
	myStreamReader.Close();
	myResponseStream.Close();
	return retString;
}
#endregion



展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部