zoukankan      html  css  js  c++  java
  • C# WebApi WebRequest/HttpWebRequest

    WebRequest如何发送http请求?

    引用

    using System.Net;
    using System.IO;

    Base on Webreqution 

            public static string WebRequestByPost(string url, string contentType, string content, string Status)
            {
                string result;
                try
                {
                    //1.Create request
                    Uri uri = new Uri(url);
                    WebRequest webRequest = WebRequest.Create(uri);
                    //2.Set request type such like "application/json; charset=UTF-8";"text/xml; charset=utf-8";
                    webRequest.ContentType = contentType;                
                    webRequest.Method = Status;//POST or Get
                    //3.If you need to set parameters or not dont need this
                    using (Stream requestStream = webRequest.GetRequestStream())
                    {
                        byte[] paramBytes = Encoding.UTF8.GetBytes(content.ToString());
                        requestStream.Write(paramBytes, 0, paramBytes.Length);
                    }
                    //4.Recived responce of request
                    WebResponse webResponse = webRequest.GetResponse();
                    using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        result = myStreamReader.ReadToEnd();
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("发送请求失败!");
                }
                return result;
            }

    总结:使用方便,简介,缺点是请求无法设置cookie。

  • 相关阅读:
    jQuery 选择器
    jQuery 语法
    jQuery 简介
    JSON 使用
    JSON 语法
    Android——Activity跳转
    Activity
    Activity2.java
    Android——Activity练习
    Andriod——手机尺寸相关的概念 +尺寸单位+关于颜色
  • 原文地址:https://www.cnblogs.com/tangpeng97/p/12981139.html
Copyright © 2011-2022 走看看