Detailed explanation of the method of integrating Net into Json to realize REST service client

  • 2021-10-24 19:21:27
  • OfStack

Preface

This article mainly introduces the related content about. Net integrating Json to realize REST service client, and shares it for your reference and study. The following words are not much to say, let's take a look at the detailed introduction.

1. Preparations

1. Click official website or download the Json plug-in Newtonsoft. Json supporting. Net4.0 locally

2. Find% compressed package%\ Bin\ net40\ Newtonsoft. Json. dll and refer to it in the project

2. Description of relevant codes

1. HttpClientUtil. cs encapsulation REST method


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  Method, automatically converted to entities based on generics, and supports 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);
  }

  //  Will  HttpWebResponse  The return result is converted to  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;
  }

  //  Get exception information  
  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  Method  
  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  Method  
  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  Method with sending content body  
  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  Method  
  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. Call the REST server method and use Json as the data format


/// <summary>
///  Object of the upgrade server url Address 
/// </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>
///  Test the connection with the upgrade server 
/// </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(" Failed to connect to remote server! ");
 }
 return rep.status == 200;
}

Summarize


Related articles: