`
独自等待戈多
  • 浏览: 35436 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

C#以Post方式访问spring的action

阅读更多

对方定义的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了。

 

以上

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics