zoukankan      html  css  js  c++  java
  • c# http Post Get 方法

    /// <summary>
    /// get方式访问webapi
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static string httpGet(string url)
    {
    try
    {
    HttpWebRequest MyRequest = (HttpWebRequest)WebRequest.Create(url);
    MyRequest.Method = "GET";
    MyRequest.Accept = "application/json";
    //返回类型可以为
    //1、application/json
    //2、text/json
    //3、application/xml
    //4、text/xml


    MyRequest.ContentType = "application/json";
    //上传类型是能为json

    string retData = null;//接收返回值
    HttpWebResponse MyResponse = (HttpWebResponse)MyRequest.GetResponse();
    if (MyResponse.StatusCode == HttpStatusCode.OK)
    {
    Stream MyNewStream = MyResponse.GetResponseStream();
    StreamReader MyStreamReader = new StreamReader(MyNewStream, Encoding.UTF8);
    retData = MyStreamReader.ReadToEnd();
    MyStreamReader.Close();
    }
    MyResponse.Close();
    return retData;
    }
    catch (Exception ex)
    {
    return ex.Message;
    }
    }

    /// <summary>
    /// post方式访问webapi
    /// </summary>
    /// <param name="url"></param>
    /// <param name="postdata"></param>
    /// <returns></returns>
    public static string httpPost(string url, string postdata)
    {
    try
    {
    HttpWebRequest MyRequest = (HttpWebRequest)WebRequest.Create(url);
    MyRequest.Method = "POST";
    MyRequest.Accept = "application/json";
    //返回类型可以为
    //1、application/json
    //2、text/json
    //3、application/xml
    //4、text/xml

    MyRequest.ContentType = "application/json";
    //上传类型是能为json

    if (postdata != null)
    {
    ASCIIEncoding MyEncoding = new ASCIIEncoding();
    byte[] MyByte = MyEncoding.GetBytes(postdata);
    Stream MyStream = MyRequest.GetRequestStream();
    MyStream.Write(MyByte, 0, postdata.Length);
    MyStream.Close();
    }

    string retData = null;//返回值
    HttpWebResponse MyResponse = (HttpWebResponse)MyRequest.GetResponse();
    if (MyResponse.StatusCode == HttpStatusCode.OK)
    {
    Stream MyNewStream = MyResponse.GetResponseStream();
    StreamReader MyStreamReader = new StreamReader(MyNewStream, Encoding.UTF8);
    retData = MyStreamReader.ReadToEnd();
    MyStreamReader.Close();
    }
    MyResponse.Close();
    return retData;
    }
    catch (Exception ex)
    {
    return ex.Message;
    }
    }

  • 相关阅读:
    覆盖方法和重载方法 C++快速入门19
    访问控制 C++快速入门18
    继承机制中的构造器和析构器 C++快速入门17
    PEInfo编程思路讲解03 工具篇03|解密系列
    静态属性和静态方法 C++快速入门21
    PEInfo编程思路讲解03 工具篇03|解密系列
    继承机制中的构造器和析构器 C++快速入门17
    覆盖方法和重载方法 C++快速入门19
    linux系统中chmod命令
    linux系统中文件、目录的权限
  • 原文地址:https://www.cnblogs.com/songconglai/p/6543233.html
Copyright © 2011-2022 走看看