其他分享
首页 > 其他分享> > 基于.Net下整合RestSharp,实现REST服务客户端

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

作者:互联网

原文地址:https://www.cnblogs.com/Mr-kevin/archive/2018/01/11/8269563.html

一. 准备工作

  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;
}
复制代码

标签:rep,upgraderClient,REST,fileReq,result,new,Net,RestSharp
来源: https://www.cnblogs.com/lizhigang/p/15523183.html