HTTP 请求,POST方式,把一个对象序列化成JSON样式作为参数访问服务器

发布时间:2020-09-03 07:16:44 作者:qiaohailun
来源:网络 阅读:3617

public static string Login(Login login)
{
HttpWebRequest request;
WebResponse response;
string remoteAddress = ConfigurationManager.AppSettings["remoteAddress"];
string LoginServiceName = ConfigurationManager.AppSettings["LoginServiceName"];

        byte[] bytes = Encoding.Default.GetBytes(string.Format("{0}@{1}:{2}", login.userid, login.factory, login.password));
        string userNamePass = Convert.ToBase64String(bytes);

        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Login));
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, login);
        var json = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
        string Authorization = "Basic " + userNamePass;
        string strPostUrl = string.Format("{0}/{1}.json", remoteAddress, LoginServiceName);
        request = (HttpWebRequest)WebRequest.Create(strPostUrl);
        request.Headers.Add("Authorization", Authorization);

        string strResponseData = String.Empty;
        byte[] bs = Encoding.ASCII.GetBytes(json);
        request.Method = "POST";
        request.Timeout = 50000;

        request.ContentType = "application/json";

        request.ContentLength = bs.Length;

        using (Stream reqStream = request.GetRequestStream())
        {
            reqStream.Write(bs, 0, bs.Length);
            reqStream.Close();
        }

        using (response = (HttpWebResponse)request.GetResponse())
        {
            using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                strResponseData = streamReader.ReadToEnd().ToString();
                if (strResponseData.Contains("success") && strResponseData.Contains("true"))
                    return Authorization;
            }
        }
        response.Close();
        return "";
    }
推荐阅读:
  1. HTTP基本原理
  2. Python3网络爬虫实战-15、爬虫基础:HTTP基本原理

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

http 请求 序列化

上一篇:Java创建和填充PDF表单域方法

下一篇:WheelView实现上下滑动选择器

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》