C#以Post方式访问spring的action

本文介绍如何使用C#扩展WebClient类以实现登录功能,并对SessionID进行加密作为通信凭证。重点在于保持Session状态,通过自定义CookieAwareWebClient类来实现在没有内置保持Session功能的情况下完成登录请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对方定义的Web接口,参数是JSON,返回也是JSON

对方服务需要登录,并且对SessionID加密作为通信凭据,系统的WebClient不具备保持Session的功能,因此对WebClient做了扩展。如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using Newtonsoft.Json.Linq;

class HttpUtil
    {
        private CookieAwareWebClient client;

        public HttpUtil()
        {
            client = new CookieAwareWebClient();
        }

        public JObject post(string url, JObject jObj)
        {
            client.Headers.Add("Content-Type", "text/html");

            string content = "[" + jObj.ToString() + "]";
            byte[] postBytes = Encoding.UTF8.GetBytes(content);

            string returnValue = "";
            try
            {
                byte[] responseArray = client.UploadData(url, "POST", postBytes);
                returnValue = Encoding.UTF8.GetString(responseArray);
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }

            returnValue = returnValue.Substring(1, returnValue.Length - 2);
            return JObject.Parse(returnValue);
           
        }

        public void dispose()
        {
            client.Dispose();
        }
    }

    class CookieAwareWebClient : WebClient
    {
        public CookieAwareWebClient()
            : this(new CookieContainer())
        { }
        public CookieAwareWebClient(CookieContainer c)
        {
            this.CookieContainer = c;
        }
        public CookieContainer CookieContainer { get; set; }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = this.CookieContainer;
            }
            return request;
        }
    }
 

C#操作JSON用到的DLL见附件。

PS:JArray是C#的JSON数组对象,调用ToString()方法时,会添加[]符号表示数组。JArray的使用和JSON类似,直接使用Parse方法即可。

PS2:貌似C#3.5自带生成JSON,不需要再使用Newtonsoft.Json了。

 

以上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值