欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.Net整合Json实现REST服务客户端的方法详解

程序员文章站 2022-04-10 11:37:37
前言 本文主要给大家介绍了关于.net整合json实现rest服务客户端的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 一. 准备工作...

前言

本文主要给大家介绍了关于.net整合json实现rest服务客户端的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

一. 准备工作

  1. 点击官网 或 本地 下载支持.net4.0 的json插件 newtonsoft.json

  2. 找到 %压缩包%\bin\net40\newtonsoft.json.dll ,在工程中引用

二. 相关代码介绍

1. httpclientutil.cs  封装rest方法

using newtonsoft.json;
using system;
using system.collections.generic;
using system.io;
using system.linq;
using system.net;
using system.text;

namespace psi.common
{
 public class httpclientutil
 {
  // rest @get 方法,根据泛型自动转换成实体,支持list<t> 
  public static t dogetmethodtoobj<t>(string url)
  {
   httpwebrequest request = (httpwebrequest)webrequest.create(url);
   request.method = "get";
   request.contenttype = "application/json;charset=utf-8";
   httpwebresponse response = null;
   try
   {
    response = (httpwebresponse)request.getresponse();
   }
   catch (webexception e)
   {
    response = (httpwebresponse)e.response;
    return default(t);
   }
   string json = getresponsestring(response);
   return jsonconvert.deserializeobject<t>(json);
  }

  // 将 httpwebresponse 返回结果转换成 string 
  private static string getresponsestring(httpwebresponse response)
  {
   string json = null;
   using (streamreader reader = new streamreader(response.getresponsestream(), system.text.encoding.getencoding("utf-8")))
   {
    json = reader.readtoend();
   }
   return json;
  }

  // 获取异常信息 
  private static string getresterrormessage(httpwebresponse errorresponse)
  {
   string errorhtml = getresponsestring(errorresponse);
   string errorkey = "unhandledexception:";
   errorhtml = errorhtml.substring(errorhtml.indexof(errorkey) + errorkey.length);
   errorhtml = errorhtml.substring(0, errorhtml.indexof("\n"));
   return errorhtml;
  }

  // rest @post 方法 
  public static t dopostmethodtoobj<t>(string url, string jsonbody)
  {
   httpwebrequest request = (httpwebrequest)webrequest.create(url);
   request.method = "post";
   request.contenttype = "application/json;charset=utf-8";
   var stream = request.getrequeststream();
   using (var writer = new streamwriter(stream))
   {
    writer.write(jsonbody);
    writer.flush();
   }
   httpwebresponse response = (httpwebresponse)request.getresponse();
   string json = getresponsestring(response);
   return jsonconvert.deserializeobject<t>(json);
  }

  // rest @put 方法 
  public static string doputmethod(string url)
  {
   httpwebrequest request = (httpwebrequest)webrequest.create(url);
   request.method = "put";
   request.contenttype = "application/json;charset=utf-8";
   httpwebresponse response = (httpwebresponse)request.getresponse();
   using (streamreader reader = new streamreader(response.getresponsestream(), system.text.encoding.getencoding("utf-8")))
   {
    return reader.readtoend();
   }
  }

  // rest @put 方法,带发送内容主体 
  public static t doputmethodtoobj<t>(string url, string jsonbody)
  {
   httpwebrequest request = (httpwebrequest)webrequest.create(url);
   request.method = "put";
   request.contenttype = "application/json;charset=utf-8";
   request.timeout = 30 * 1000;
   var stream = request.getrequeststream();
   using (var writer = new streamwriter(stream))
   {
    writer.write(jsonbody);
    writer.flush();
   }
   httpwebresponse response = (httpwebresponse)request.getresponse();
   string json = getresponsestring(response);
   return jsonconvert.deserializeobject<t>(json);
  }

  // rest @delete 方法 
  public static bool dodeletemethod(string url)
  {
   httpwebrequest request = (httpwebrequest)webrequest.create(url);
   request.method = "delete";
   request.contenttype = "application/json;charset=utf-8";
   httpwebresponse response = (httpwebresponse)request.getresponse();
   using (streamreader reader = new streamreader(response.getresponsestream(), system.text.encoding.getencoding("utf-8")))
   {
    string responsestring = reader.readtoend();
    if (responsestring.equals("1"))
    {
     return true;
    }
    return false;
   }
  } 
 }
}

2. 调用rest服务端方法,以json作为数据格式

/// <summary>
/// 取得升级服务端的url地址
/// </summary>
/// <returns></returns>
private string getserverurl()
{
 string result = "";
 upgraderclient upgraderclient = getupgraderclient();
 if (upgraderclient != null)
 {
  result += "http://" + upgraderclient.serverip +
   ":" + upgraderclient.serverport +
   "/upgraderserver/service/upgrade.do";
 }
 return result;
}

/// <summary>
/// 测试与升级服务端的连接
/// </summary>
/// <returns></returns>
public bool testconnect()
{
 filerequest filereq = new filerequest();
 filereq.type = (int)requesttype.test_connect;
 string jsondata = jsonconvert.serializeobject(filereq);
 fileresponse rep = null;
 try
 {
  rep = httpclientutil.dopostmethodtoobj<fileresponse>(getserverurl(), jsondata);
 } catch
 {
  throw new exception("连接远程服务端失败!");
 }
 return rep.status == 200;
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。