C # Netcore HTTP request package

public class NewHttpClient2

{
public enum BodyFormat
{
Formed, Json
}
public BodyFormat BodyType;
public string Method;
public Uri Uri;
public Encoding ContentEncoding;
public Dictionary<string, object> Bodys;
public Dictionary<string, string> Headers;
public Dictionary<string, string> Querys;
public int Timeout;
private NewHttpClient2()
{
BodyType
= BodyFormat.Formed;
Method
= "GET";
ContentEncoding
= Encoding.UTF8;
Bodys
= new Dictionary<string, object>();
Headers
= new Dictionary<string, string>();
Querys
= new Dictionary<string, string>();
ServicePointManager.Expect100Continue
= false;
Timeout
= 60000;
}
public NewHttpClient2(string uri): this()
{
Uri
= new Uri(uri);
}
public HttpWebRequest HttpWebRequest;
public string UriWithQuery
{
get
{
return Uri + "?" + Util.ParseQueryString(Querys);
}
}
public JObject PostAction()
{
HttpWebRequest
= (HttpWebRequest)WebRequest.Create(UriWithQuery);
HttpWebRequest.Method
= Method;
HttpWebRequest.ReadWriteTimeout
= 30000;
foreach (var header in Headers)
{
HttpWebRequest.Headers.Add(header.Key, header.Value);
}
byte[] body = null;
switch (BodyType)
{
case BodyFormat.Formed:
{
var bodydata = Bodys.Select(pair => pair.Key + "=" + Util.UriEncode(pair.Value.ToString()))
.DefaultIfEmpty(
"")
.Aggregate((a, b)
=> a + "& " + b);
body
= ContentEncoding.GetBytes(bodydata);
HttpWebRequest.ContentType
= "application/x-www-form-urlencoded ";
break;
}
case BodyFormat.Json:
{
var bodydata = JsonConvert.SerializeObject(Bodys);
body
= ContentEncoding.GetBytes(bodydata);
HttpWebRequest.ContentType
= "application/json";
break;
}
}
if (body != null && Bodys.Count > 0)
{
var stream = HttpWebRequest.GetRequestStream();
stream.Write(body,
0, body.Length);
stream.Close();
}
HttpWebResponse webresp;
try
{
webresp
= (HttpWebResponse)HttpWebRequest.GetResponse();
}
catch (WebException e)
{
//Request failed
throw new ApiException((int)e.Status, e.Message);
}
if (webresp.StatusCode != HttpStatusCode.OK)
{
throw new ApiException((int)webresp.StatusCode, "Server response code: " + (int)webresp.StatusCode);
}
var respdata = Util.StreamToString(webresp.GetResponseStream(), ContentEncoding );
JObject respJobject;
try
{
respJobject
= JsonConvert.DeserializeObject(respdata);
}
catch (Exception e)
{
throw new ApiException(e.Message + ":" + respdata);
}
if (respJobject == null)
{
throw new ApiException("Empty response!");
}
return respJobject;
}
}
public static string StreamToString(Stream ss, Encoding enc)

{
string ret;
using (var reader = new StreamReader(ss, enc))
{
ret
= reader.ReadToEnd();
}
ss.Close();
return ret;
}
public static string UriEncode(string input, bool encodeSlash = < span style="color: #0000ff;">false)
{
var builder = new StringBuilder();
foreach (var b in Encoding.UTF8.GetBytes(input))
if (b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b> = '0' span> && b <= '9' || b == '_' || b == '- ||
b
== '~' || b == '.')
builder.Append((
char)b);
else if (b == '/')
if (encodeSlash)
builder.Append(
"%2F");
else
builder.Append((
char)b);
else
builder.Append(
'%').Append(b.ToString(" X2"));
return builder.ToString();
}
public static string ParseQueryString(Dictionary<string, string>< span style="color: #000000;"> querys)
{
if (querys.Count == 0)
return "";
return querys
.Select(pair
=> pair.Key + "=" + pair.Value)
.Aggregate((a, b)
=> a + "& " + b);
}



try

{
var a = new NewHttpClient2("http://localhost:100/.well-known/openid-configuration");
var b = a.PostAction();
var c = new NewHttpClient2(b["token_endpoint"< span style="color: #000000;">].ToString())
{
Bodys = new Dictionary<string, object> {{"scope", "api1< /span>" }, {"grant_type", "password" },{"client_id","ro.client" },
{
"client_secret","secret" },{ "username< span style="color: #800000;">"
,"alice"},{" password","password"} },
Method
= "POST"
};
var d = c.PostAction();
var e = new NewHttpClient2("http://localhost:101/api/values/get") {
BodyType
=NewHttpClient2.BodyFormat.Json,
Headers
=new Dictionary<string, string> {{"Authorization", d[" token_type"].ToString() + " " + d["access_token< span style="color: #800000;">"].ToString()}}
};
var f = e.PostAction();
return Ok(f);
}
catch (ApiException e)
{
return Ok(e);
}
catch(Exception e)
{
return Ok(e);
}

[Serializable]

public class ApiException:Exception
{
public int Code {get; set;}
public ApiException()
{
Code
= -1;
}
public ApiException(string message): base(message)
{

}
public ApiException(int code, string message): base(message)
{
Code
= code;
}
}

public

span> static string StreamToString( Stream ss, Encoding enc)
{
string ret;
using (var reader = new StreamReader(ss, enc))
{
ret
= reader.ReadToEnd();
}
ss.Close();
return ret;
}
public static string UriEncode(string input, bool encodeSlash = < span style="color: #0000ff;">false
)
{
var builder = new StringBuilder();
foreach (var b in Encoding.UTF8.GetBytes(input))
if (b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b> = '0' span> && b <= '9' || b == '_' || b == '- ||
b
== '~' || b == '.')
builder.Append((
char)b);
else if (b == '/')
if (encodeSlash)
builder.Append(
"%2F");
else
builder.Append((
char)b);
else
builder.Append(
'%').Append(b.ToString(" X2"));
return builder.ToString();
}
public static string ParseQueryString(Dictionary<string, string>< span style="color: #000000;"> querys)
{
if (querys.Count == 0)
return "";
return querys
.Select(pair
=> pair.Key + "=" + pair.Value)
.Aggregate((a, b)
=> a + "& " + b);
}

I am thinking about the new http encapsulation method again. This, it is estimated to be more complete, the returned data can be converted to jobject by default. Otherwise modify the postaction under

public class

span> NewHttpClient2
{
public enum BodyFormat
{
Formed, Json
}
public BodyFormat BodyType;
public string Method;
public Uri Uri;
public Encoding ContentEncoding;
public Dictionary<string, object> Bodys;
public Dictionary<string, string> Headers;
public Dictionary<string, string> Querys;
public int Timeout;
private NewHttpClient2()
{
BodyType
= BodyFormat.Formed;
Method
= "GET";
ContentEncoding
= Encoding.UTF8;
Bodys
= new Dictionary<string, object>();
Headers
= new Dictionary<string, string>();
Querys
= new Dictionary<string, string>();
ServicePointManager.Expect100Continue
= false;
Timeout
= 60000;
}
public NewHttpClient2(string uri): this()
{
Uri
= new Uri(uri);
}
public HttpWebRequest HttpWebRequest;
public string UriWithQuery
{
get
{
return Uri + "?" + Util.ParseQueryString(Querys);
}
}
public JObject PostAction()
{
HttpWebRequest
= (HttpWebRequest)WebRequest.Create(UriWithQuery);
HttpWebRequest.Method
= Method;
HttpWebRequest.ReadWriteTimeout
= 30000;
foreach (var header in Headers)
{
HttpWebRequest.Headers.Add(header.Key, header.Value);
}
byte[] body = null;
switch (BodyType)
{
case BodyFormat.Formed:
{
var bodydata = Bodys.Select(pair => pair.Key + "=" + Util.UriEncode(pair.Value.ToString()))
.DefaultIfEmpty(
"")
.Aggregate((a, b)
=> a + "&" + b);
body
= ContentEncoding.GetBytes(bodydata);
HttpWebRequest.ContentType
= "application/x-www-form-urlencoded";
break;
}
case BodyFormat.Json:
{
var bodydata = JsonConvert.SerializeObject(Bodys);
body
= ContentEncoding.GetBytes(bodydata);
HttpWebRequest.ContentType
= "application/json";
break;
}
}
if (body != null && Bodys.Count > 0)
{
var stream = HttpWebRequest.GetRequestStream();
stream.Write(body,
0, body.Length);
stream.Close();
}
HttpWebResponse webresp;
try
{
webresp
= (HttpWebResponse)HttpWebRequest.GetResponse();
}
catch (WebException e)
{
//请求失败
throw new ApiException((int)e.Status, e.Message);
}
if (webresp.StatusCode != HttpStatusCode.OK)
{
throw new ApiException((int)webresp.StatusCode, "Server response code:" + (int)webresp.StatusCode);
}
var respdata = Util.StreamToString(webresp.GetResponseStream(), ContentEncoding);
JObject respJobject;
try
{
respJobject
= JsonConvert.DeserializeObject(respdata);
}
catch (Exception e)
{
throw new ApiException(e.Message + ":" + respdata);
}
if (respJobject == null)
{
throw new ApiException("Empty response!");
}
return respJobject;
}
}
public static string StreamToString(Stream ss, Encoding enc)

{
string ret;
using (var reader = new StreamReader(ss, enc))
{
ret
= reader.ReadToEnd();
}
ss.Close();
return ret;
}
public static string UriEncode(string input, bool encodeSlash = false)
{
var builder = new StringBuilder();
foreach (var b in Encoding.UTF8.GetBytes(input))
if (b >= a && b <= z || b >= A && b <= Z || b >= 0 && b <= 9 || b == _ || b == - ||
b
== ~ || b == .)
builder.Append((
char)b);
else if (b == /)
if (encodeSlash)
builder.Append(
"%2F");
else
builder.Append((
char)b);
else
builder.Append(
%).Append(b.ToString("X2"));
return builder.ToString();
}
public static string ParseQueryString(Dictionary<string, string> querys)
{
if (querys.Count == 0)
return "";
return querys
.Select(pair
=> pair.Key + "=" + pair.Value)
.Aggregate((a, b)
=> a + "&" + b);
}


 


public static string StreamToString(Stream ss, Encoding enc)

{
string ret;
using (var reader = new StreamReader(ss, enc))
{
ret
= reader.ReadToEnd();
}
ss.Close();
return ret;
}
public static string UriEncode(string input, bool encodeSlash = false)
{
var builder = new StringBuilder();
foreach (var b in Encoding.UTF8.GetBytes(input))
if (b >= a && b <= z || b >= A && b <= Z || b >= 0 && b <= 9 || b == _ || b == - ||
b
== ~ || b == .)
builder.Append((
char)b);
else if (b == /)
if (encodeSlash)
builder.Append(
"%2F");
else
builder.Append((
char)b);
else
builder.Append(
%).Append(b.ToString("X2"));
return builder.ToString();
}
public static string ParseQueryString(Dictionary<string, string> querys)
{
if (querys.Count == 0)
return "";
return querys
.Select(pair
=> pair.Key + "=" + pair.Value)
.Aggregate((a, b)
=> a + "&" + b);
}

try

{
var a = new NewHttpClient2("http://localhost:100/.well-known/openid-configuration");
var b = a.PostAction();
var c = new NewHttpClient2(b["token_endpoint"].ToString())
{
Bodys
= new Dictionary<string, object> { { "scope", "api1" }, { "grant_type", "password" },{"client_id","ro.client" },
{
"client_secret","secret" },{ "username","alice"},{"password","password" } },
Method
= "POST"
};
var d = c.PostAction();
var e = new NewHttpClient2("http://localhost:101/api/values/get") {
BodyType
=NewHttpClient2.BodyFormat.Json,
Headers
=new Dictionary<string, string> { {"Authorization", d["token_type"].ToString() + " " + d["access_token"].ToString() } }
};
var f = e.PostAction();
return Ok(f);
}
catch (ApiException e)
{
return Ok(e);
}
catch(Exception e)
{
return Ok(e);
}

[Serializable]

public class ApiException:Exception
{
public int Code { get; set; }
public ApiException()
{
Code
= -1;
}
public ApiException(string message) : base(message)
{

}
public ApiException(int code, string message) : base(message)
{
Code
= code;
}
}

public static string StreamToString(Stream ss, Encoding enc)

{
string ret;
using (var reader = new StreamReader(ss, enc))
{
ret
= reader.ReadToEnd();
}
ss.Close();
return ret;
}
public static string UriEncode(string input, bool encodeSlash = false)
{
var builder = new StringBuilder();
foreach (var b in Encoding.UTF8.GetBytes(input))
if (b >= a && b <= z || b >= A && b <= Z || b >= 0 && b <= 9 || b == _ || b == - ||
b
== ~ || b == .)
builder.Append((
char)b);
else if (b == /)
if (encodeSlash)
builder.Append(
"%2F");
else
builder.Append((
char)b);
else
builder.Append(
%).Append(b.ToString("X2"));
return builder.ToString();
}
public static string ParseQueryString(Dictionary<string, string> querys)
{
if (querys.Count == 0)
return "";
return querys
.Select(pair
=> pair.Key + "=" + pair.Value)
.Aggregate((a, b)
=> a + "&" + b);
}

Leave a Comment

Your email address will not be published.