zoukankan      html  css  js  c++  java
  • json参数http post请求

    /// <summary>
    /// post请求
    /// </summary>
    /// <param name="Url"></param>
    /// <param name="jsonParas"></param>
    /// <returns></returns>
    public string Post(string jsonParas)
    {
    string strURL = baseUrl;
    //创建一个HTTP请求
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
    //Post请求方式
    request.Method = "POST";
    //内容类型
    request.ContentType = "application/json";

    //设置参数,并进行URL编码
    string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);

    byte[] payload;
    //将Json字符串转化为字节
    payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
    //设置请求的ContentLength
    request.ContentLength = payload.Length;
    //发送请求,获得请求流

    Stream writer;
    try
    {
    writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
    }
    catch (Exception)
    {
    writer = null;
    Console.Write("连接服务器失败!");
    }
    //将请求参数写入流
    writer.Write(payload, 0, payload.Length);
    writer.Close();//关闭请求流
    // String strValue = "";//strValue为http响应所返回的字符流
    HttpWebResponse response;
    try
    {
    //获得响应流
    response = (HttpWebResponse)request.GetResponse();
    }
    catch (WebException ex)
    {
    response = ex.Response as HttpWebResponse;
    }
    Stream s = response.GetResponseStream();
    // Stream postData = Request.InputStream;
    StreamReader sRead = new StreamReader(s);
    string postContent = sRead.ReadToEnd();
    sRead.Close();
    return postContent;//返回Json数据
    }

  • 相关阅读:
    JAVA_SE基础——47.接口
    抽象类和接口的区别[精华版]
    JAVA_SE基础——46.引用数据类型变量.值交换[独家深入解析]
    JAVA_SE基础——45.基本类型变量.值交换[独家深入解析]
    第一个Spring程序
    三层架构和MVC的区别
    Spring 概述及IOC理论推导
    Mybatis之缓存
    Mybatis之动态SQL
    Mybatis之一对多和多对一处理
  • 原文地址:https://www.cnblogs.com/llsade/p/14846090.html
Copyright © 2011-2022 走看看