zoukankan      html  css  js  c++  java
  • C# 发起Get和Post请求

    public class ApiHelper
        {
         //contentType application/json or application/xml
    public string HttpGet(string Url, string contentType) { try { string retString = string.Empty; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "GET"; request.ContentType = contentType; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(myResponseStream); retString = streamReader.ReadToEnd(); streamReader.Close(); myResponseStream.Close(); return retString; } catch (Exception ex) { throw ex; } } public static string HttpPost(string Url, string postDataStr, string contentType, out bool isOK) { string retString = string.Empty; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = contentType; request.Timeout = 600000;//设置超时时间 request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr); Stream requestStream = request.GetRequestStream(); StreamWriter streamWriter = new StreamWriter(requestStream); streamWriter.Write(postDataStr); streamWriter.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream); retString = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); isOK = true; } catch (Exception ex) { if (ex.GetType() == typeof(WebException))//捕获400错误 { var response = ((WebException)ex).Response; Stream responseStream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream); retString = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); } else { retString = ex.ToString(); } isOK = false; } return retString; } }
  • 相关阅读:
    javascript和C#比较
    前端模块管理器简介
    javascript中的splice方法介绍&示例
    javascript中数组揭秘
    17款code review工具
    IIS ip访问限制插件
    iis 限制动态IP地址访问次数
    AWS云使用100条宝贵经验分享
    C# 开源框架(整理)
    如何获取Azure AD tenant的tenant Id?
  • 原文地址:https://www.cnblogs.com/nicopoiduang/p/10818374.html
Copyright © 2011-2022 走看看