• c# http get请求与post请求实例


    //http请求工具类

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;

    namespace HttpTest
    {
    class HttpUtil
    {

    /// <summary>
    /// get请求
    /// </summary>
    /// <param name="url">网络地址</param>
    /// <param name="parm">参数</param>
    /// <returns></returns>
    public static string HttpGet(string url,string parm){

    return HttpRequest(url,parm,"GET");

    }

    /// <summary>
    /// post请求
    /// </summary>
    /// <param name="url">网络地址</param>
    /// <param name="parm">参数</param>
    /// <returns></returns>
    public static string HttpPost(string url,string parm) {

    return HttpRequest(url,parm,"POST");
    }

    /// <summary>
    /// 网络请求
    /// </summary>
    /// <param name="url">网络地址</param>
    /// <param name="parm">参数</param>
    /// <param name="method">请求方式</param>
    /// <returns></returns>
    private static string HttpRequest(string url, string parm, string method)
    {

    if(method.Equals("GET")){

    url = url + "?" + parm;
    }
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = method;
    request.Timeout = 5 * 1000;
    request.AllowWriteStreamBuffering = true;
    request.AllowWriteStreamBuffering = true;
    request.ContentType = "text/html;charset=UTF-8";
    // request.ContentType = "application/x-www-form-urlencoded";
    if (method.Equals("POST"))
    {
    StreamWriter wr = new StreamWriter(request.GetRequestStream(), Encoding.UTF8);
    wr.Write(parm);
    wr.Flush();
    wr.Close();
    }

    HttpWebResponse respone = (HttpWebResponse)request.GetResponse();
    var stream = respone.GetResponseStream();
    StreamReader red = new StreamReader(stream, Encoding.UTF8);
    string str = red.ReadToEnd();
    red.Close();
    stream.Flush();
    stream.Close();
    return str;
    }
    }
    }

    //调用示例

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace HttpTest
    {
    class Program
    {
    static void Main(string[] args)
    {
    Console.WriteLine(HttpUtil.HttpGet("https://hao.360.cn/?s0001",""));
    }
    }
    }

  • 相关阅读:
    Linux系统下用mail(mailx)发送邮件
    Docker+Nginx+KeepaLived 简单实现Nginx高可用+负载均衡
    MySql安装(Windows版本)
    十分钟入门Git和GitHub的源码版本管理
    Sql Server数据库读写分离配置
    C 语言中的 printf() 和 scanf() 简介
    C 语言字符串简介
    C 语言概述
    初识 C 语言
    计算机中的存储器
  • 原文地址:https://www.cnblogs.com/zzjbk/p/5341627.html
Copyright © 2020-2023  润新知