Skip to content

Instantly share code, notes, and snippets.

@xujiesh0510
Last active June 26, 2017 13:52
Show Gist options
  • Save xujiesh0510/2d538816217171a3853cb7d0a8ffedf7 to your computer and use it in GitHub Desktop.
Save xujiesh0510/2d538816217171a3853cb7d0a8ffedf7 to your computer and use it in GitHub Desktop.
use IHttpHandler and HttpClient to Create Request Proxy For another Site
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
namespace Console.handler
{
/// <summary>
/// Handler 的摘要说明
/// </summary>
public class Handler : IHttpHandler
{
public static readonly string TargetUrl ="http://"+ ConfigurationManager.AppSettings["JBPMHost"]+ ":"+ConfigurationManager.AppSettings["JBPMPort"]+ConfigurationManager.AppSettings["JBPMRoot"];
public static readonly string TargetHost = ConfigurationManager.AppSettings["JBPMHost"] + ":" + ConfigurationManager.AppSettings["JBPMPort"] + ConfigurationManager.AppSettings["JBPMRoot"];
public void ProcessRequest(HttpContext context)
{
try
{
HttpClientVersion(context);
}
catch (HttpUnSuccessException ex)
{
context.Response.StatusCode = ex.StatusCode;
context.Response.Write(ex.ResponseText);
}
}
public bool IsReusable => false;
public void HttpClientVersion(HttpContext context)
{
var url = context.Request.RawUrl;
url = url.TrimStart("/workflow");
url = url.TrimStart("/editor");
url = url.TrimStart("/idm");
url ="http://admin:test@"+ TargetHost + url;
var verbMethod = context.Request.HttpMethod;
var handler = new HttpClientHandler {CookieContainer = new CookieContainer()};
using (var httpClient = new HttpClient(handler))
{
var responseText = string.Empty;
ComposeRequestEnv(httpClient, context, handler);
if (verbMethod == "GET")
{
var responseMessage = httpClient.GetAsync(url).Result;
if (responseMessage.StatusCode == HttpStatusCode.Unauthorized)
{
throw new HttpUnSuccessException(401, "");
}
try
{
responseText = responseMessage.Content.ReadAsStringAsync().Result;
responseMessage.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
throw new HttpUnSuccessException((int)responseMessage.StatusCode, responseText);
}
var stream = responseMessage.Content.ReadAsStreamAsync().Result;
stream.CopyTo(context.Response.OutputStream);
if (responseMessage.Content.Headers.ContentType?.MediaType != null)
context.Response.ContentType = responseMessage.Content.Headers.ContentType.MediaType;
return;
}
MediaTypeHeaderValue mediaType;
var streamContent = new StreamContent(context.Request.InputStream);
if (MediaTypeHeaderValue.TryParse(context.Request.ContentType, out mediaType))
streamContent.Headers.ContentType = mediaType;
HttpResponseMessage response = null;
if (verbMethod == "POST")
response = httpClient.PostAsync(url, streamContent).Result;
else if (verbMethod == "DELETE")
response = httpClient.DeleteAsync(url).Result;
else if (verbMethod == "PUT")
response = httpClient.PutAsync(url, streamContent).Result;
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new HttpUnSuccessException(401,"");
}
try
{
responseText = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
throw new HttpUnSuccessException((int)response.StatusCode, responseText);
}
if (response.Content.Headers.ContentType?.MediaType != null)
context.Response.ContentType = response.Content.Headers.ContentType.MediaType;
var responseStream = response.Content.ReadAsStreamAsync().Result;
responseStream.CopyTo(context.Response.OutputStream);
var responseCookies = handler.CookieContainer.GetCookies(new Uri(TargetUrl));
for (var i = 0; i < responseCookies.Count; i++)
{
var ck = new HttpCookie(responseCookies[i].Name, responseCookies[i].Value);
context.Response.Cookies.Remove(ck.Name);
context.Response.Cookies.Add(ck);
}
}
}
private static void ComposeRequestEnv(HttpClient httpClient, HttpContext context, HttpClientHandler handler)
{
var cookies = context.Request.Cookies;
httpClient.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident / 6.0)");
httpClient.DefaultRequestHeaders.Host = ConfigurationManager.AppSettings["JBPMHost"];
httpClient.DefaultRequestHeaders.Connection.ParseAdd("keep-alive");
httpClient.DefaultRequestHeaders.Pragma.ParseAdd("no-cache");
httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/json, text/plain, */*");
httpClient.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue
{
NoCache = true,
NoStore = true,
MustRevalidate = true
};
httpClient.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, sdch, br");
httpClient.DefaultRequestHeaders.AcceptLanguage.ParseAdd("zh-CN,zh;q=0.8");
for (var i = 0; i < cookies.Count; i++)
{
var cookie = new Cookie(cookies[i].Name, cookies[i].Value, "/");
handler.CookieContainer.Add(new Uri(TargetUrl), cookie); // Adding a Cookie
}
var byteArray = Encoding.ASCII.GetBytes("admin:test");
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment