美文网首页
C#(c sharp)的request和post

C#(c sharp)的request和post

作者: Magna | 来源:发表于2019-05-28 08:38 被阅读0次

    POST data部分:

    public string PostUrl(string url,string postData)      //url:请求地址;postData:post data数据
    { 
      string result = "";  //定义返回数据,为json数据
      HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
      req.Method = "POST";
      req.Timeout = 800;
      req.ContentType = ''application/json";
      byte[] data = Encoding.UTF8.GetBytes(postData);
      req.ContentLength = data.Length;
      using (Stream reqStream = req.GetRequestStream()){
        reqStream.Write(data,0,data.Length);
        reqStream.Close();
      }
    
      try
      {
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        Stream stream = resp.GetResponseStream();
      
        using (StreamReader reader = new StreamReader(stream,Encoding.UTF8))
        { 
          result = reader.ReadToEnd();
        }
        resp.Close()
        stream.Close();
      }
      catch
      {  
        
      }
      return result;
    
     }
    
    

    关于POST DATA的构造

    string jsonpost = "{\"keyword\":\"value\"}"    //实际上就是把\"作为双引号使用
    

    如果仅仅是request地址:

    public string justRequest(string url){
        string result = "";
        try
        { 
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            Stream receiveStream = res.GetResponseStream();
            StreamReader reader = new StreamReader(receiveStream,Encoding.UTF8)
            returnstr = reader.ReadToEnd();
        }
        catch
        {
      
         }
        return returnstr;
    }
    

    提示:以上内容如有疑问请留言,或emal:zhanlanxinxi@163.com

    相关文章

      网友评论

          本文标题:C#(c sharp)的request和post

          本文链接:https://www.haomeiwen.com/subject/ecoltctx.html