基于.Net下整合RestSharp,实现REST服务客户端

一. 准备工作

  1. 点击此访问 RestSharp 官网,可作参考

  2. VS2012 中安装支持.Net4.0的最新版 RestSharp 插件

    工具---NuGet程序包管理器---程序包管理器控制台,输入如下命令

Install-Package RestSharp -Version 105.2.3

 

二. 相关代码介绍

  1. 消费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;
    FileResponse rep = null;
    try
    {
        RestClient client = new RestClient(getServerUrl());
        RestRequest request = new RestRequest(Method.POST);
        request.AddJsonBody(fileReq);
        RestResponse<FileResponse> response = (RestResponse<FileResponse>)client.Execute<FileResponse>(request);
        rep = response.Data;
    } catch
    {
        throw new Exception("连接远程服务端失败!");
    }
    return rep.status == 200;
}
View Code

 

posted on 2018-01-11 17:36 大饼酥 阅读(...) 评论(...) 编辑 收藏

导航

统计

公告