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 , str
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) { //请求失败 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<JObject>(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); }
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); }
又琢磨http新封装方法了,这个,估计更完善些,返回数据默认能转换为jobject,不然修改postaction下