C#(c sharp)的request和post

2019-05-28  本文已影响0人  Magna

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

上一篇下一篇

猜你喜欢

热点阅读