WebApi实现代理Http请求
【摘要】
h5调用第三方api时候经常遇到不允许跨域的问题,用webapi实现一个代理http接口,方便进行跨域请求。
using Newtonsoft.Json;using Newtonsoft.Json.Linq;using System;using System.Collections.Generic;using System.IO;us...
h5调用第三方api时候经常遇到不允许跨域的问题,用webapi实现一个代理http接口,方便进行跨域请求。
-
using Newtonsoft.Json;
-
using Newtonsoft.Json.Linq;
-
using System;
-
using System.Collections.Generic;
-
using System.IO;
-
using System.Linq;
-
using System.Net;
-
using System.Net.Http;
-
using System.Net.Http.Headers;
-
using System.Web.Http;
-
using YFAPICommon.Models;
-
-
namespace YFAPICommon.Controllers
-
{
-
public class HttpInput
-
{
-
public string url { set; get; }
-
public Dictionary<string,object> param { set; get; }
-
}
-
public class HttpProxyController : ApiController
-
{
-
public object doPost(HttpInput input)
-
{
-
if (string.IsNullOrWhiteSpace(input.url))
-
return ReturnNode.ReturnError("url不能为空");
-
if (input.param == null)
-
input.param = new Dictionary<string, object>();
-
string result = Post(input.url,input.param);
-
if (result != null)
-
{
-
try
-
{
-
JObject obj = JsonConvert.DeserializeObject<JObject>(result);
-
return obj;
-
}
-
catch (Exception ex)
-
{
-
}
-
}
-
return result;
-
}
-
-
public object doGet(HttpInput input)
-
{
-
if (string.IsNullOrWhiteSpace(input.url))
-
return ReturnNode.ReturnError("url不能为空");
-
if (input.param == null)
-
input.param = new Dictionary<string, object>();
-
string result = Get(input.url);
-
if (result != null)
-
{
-
try
-
{
-
JObject obj = JsonConvert.DeserializeObject<JObject>(result);
-
return obj;
-
}
-
catch (Exception ex)
-
{
-
}
-
}
-
return result;
-
}
-
-
private static string Post(string url, Dictionary<string, object> param)
-
{
-
using (HttpClient client = new HttpClient())
-
{
-
//请求超时
-
//client.Timeout = new TimeSpan(5000);
-
-
var httpContent = new StringContent(JsonConvert.SerializeObject(param));
-
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
-
-
var response = client.PostAsync(url, httpContent).Result;
-
var responseValue = response.Content.ReadAsStringAsync().Result;
-
if (response.StatusCode == System.Net.HttpStatusCode.OK)
-
{
-
return responseValue;
-
}
-
-
return null;
-
}
-
}
-
-
private static string Get(string url)
-
{
-
-
var request = (HttpWebRequest)WebRequest.Create(url);
-
var response = (HttpWebResponse)request.GetResponse();
-
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
-
if (response.StatusCode == System.Net.HttpStatusCode.OK)
-
{
-
return responseString;
-
}
-
-
return null;
-
}
-
}
-
}
文章来源: zzzili.blog.csdn.net,作者:清雨小竹,版权归原作者所有,如需转载,请联系作者。
原文链接:zzzili.blog.csdn.net/article/details/101421833
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)