博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HttpWebRequest和WebClient的用法
阅读量:5075 次
发布时间:2019-06-12

本文共 4219 字,大约阅读时间需要 14 分钟。

//通过web方式,从远程服务器端下载文件:

public static void DownLoad(string Url, string FileName, string machinetype)
{
try
{
if (Url.Contains("http"))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();

System.Drawing.Image downImage = System.Drawing.Image.FromStream(request.GetResponse().GetResponseStream());

string imageUrl = ConfigurationManager.AppSettings["imageUrl"];

string dertory = Path.Combine(imageUrl, machinetype);
string fileName = string.Format("{0}.png", FileName);
if (!System.IO.Directory.Exists(dertory))
{
System.IO.Directory.CreateDirectory(dertory);
}
downImage.Save(dertory + "\\" + fileName);
downImage.Dispose();
}
else
{
return;
}
}
catch (Exception ex)
{
DataAccess.WriteLog(ex.Message + ": Url: " + Url + ", systemtwoid: " + FileName + ", CFTname: " + machinetype + " " + ex.StackTrace, "DownLoad");
return;

}

}
///WebClient
public static string PostMobileApi(string fun, string token, string data)
{
string TYCSR_url = ConfigurationManager.AppSettings["TYCSR"].ToString();
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.Encoding = Encoding.UTF8;
//string url = "http://localhost:8084/api/ApiIndex/main";//

string postData = "fun=" + fun + "&token=5D993541B0E4BC9193CA17CDF191E6C1&vst=2&way=2&ver=1.0&data=" + data;

string result = client.UploadString(TYCSR_url, "POST", postData);
return result;
}
//HttpWebRequest post请求数据
public static string PostFormData(string password, string username)
{
string rst = "";
Dictionary<string, string> input = new Dictionary<string, string>();
input.Add("client_id", "" + ConfigurationSettings.AppSettings["client_id"].ToString() + "");
input.Add("client_secret", "" + ConfigurationSettings.AppSettings["client_secret"].ToString() + "");
input.Add("grant_type", "" + ConfigurationSettings.AppSettings["grant_type"].ToString() + "");
input.Add("password", "" + password + "");
input.Add("scope", "" + ConfigurationSettings.AppSettings["scope"].ToString() + "");
input.Add("username", "" + username + "");
input.Add("oauth_nonce", "9");
input.Add("sysId", "1");

string oAuthUrl = ConfigurationSettings.AppSettings["oauthUrl"].ToString();
string url = oAuthUrl + "connect/token";

string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Expect = "";
MemoryStream stream = new MemoryStream();

byte[] line = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");

byte[] enterER = Encoding.ASCII.GetBytes("\r\n");

//提交文本字段

if (input != null)
{
string format = "--" + boundary + "\r\nContent-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}\r\n"; //自带项目分隔符
foreach (string key in input.Keys)
{
string s = string.Format(format, key, input[key]);
byte[] data = Encoding.UTF8.GetBytes(s);
stream.Write(data, 0, data.Length);
}
}

byte[] foot_data = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); //项目最后的分隔符字符串需要带上--

stream.Write(foot_data, 0, foot_data.Length);

request.ContentLength = stream.Length;

Stream requestStream = request.GetRequestStream(); //写入请求数据
stream.Position = 0L;
stream.WriteTo(requestStream);
stream.Close();

requestStream.Close();

try

{
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
try
{
using (var responseStream = response.GetResponseStream())
using (var mstream = new MemoryStream())
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8, true, 100);
rst = @"[" + reader.ReadToEnd() + "]";
reader.Close();
response.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
catch (WebException ex)
{
throw ex;
}
}
catch (Exception ex)
{
throw ex;
}

//解析数据,返回token值

List<GetPersonAccounts> jobInfoList = JsonConvert.DeserializeObject<List<GetPersonAccounts>>(rst);
GetPersonAccounts personAccounts = new GetPersonAccounts();

foreach (GetPersonAccounts perAccount in jobInfoList)

{
personAccounts.access_token = perAccount.access_token;
}

return personAccounts.access_token;

}

转载于:https://www.cnblogs.com/laolin/p/9406967.html

你可能感兴趣的文章
Jquery ui widget开发
查看>>
关于indexOf的使用
查看>>
英语单词
查看>>
centos6.8下安装matlab2009(图片转帖)
查看>>
Mongo自动备份
查看>>
cer证书签名验证
查看>>
新手Python第一天(接触)
查看>>
【bzoj1029】[JSOI2007]建筑抢修
查看>>
synchronized
查看>>
codevs 1080 线段树练习
查看>>
[No0000195]NoSQL还是SQL?这一篇讲清楚
查看>>
【深度学习】caffe 中的一些参数介绍
查看>>
Python-Web框架的本质
查看>>
QML学习笔记之一
查看>>
Window 的引导过程
查看>>
App右上角数字
查看>>
从.NET中委托写法的演变谈开去(上):委托与匿名方法
查看>>
小算法
查看>>
201521123024 《java程序设计》 第12周学习总结
查看>>
新作《ASP.NET MVC 5框架揭秘》正式出版
查看>>