c# POST和GET方式通过服务器地址提交数据
2020-12-13 14:36
标签:des style blog http io os ar for sp 1:POST方式提交:
c# POST和GET方式通过服务器地址提交数据 标签:des style blog http io os ar for sp 原文地址:http://blog.csdn.net/make1828/article/details/40649759private static string HttpPostConnectToServer(string serverUrl, string postData)
{
var dataArray = Encoding.UTF8.GetBytes(postData);
//创建请求
var request = (HttpWebRequest)HttpWebRequest.Create(serverUrl);
request.Method = "POST";
request.ContentLength = dataArray.Length;
//设置上传服务的数据格式
request.ContentType = "application/x-www-form-urlencoded";
//请求的身份验证信息为默认
request.Credentials = CredentialCache.DefaultCredentials;
//请求超时时间
request.Timeout = 10000;
//创建输入流
Stream dataStream;
//using (var dataStream = request.GetRequestStream())
//{
// dataStream.Write(dataArray, 0, dataArray.Length);
// dataStream.Close();
//}
try
{
dataStream = request.GetRequestStream();
}
catch (Exception)
{
return null;//连接服务器失败
}
//发送请求
dataStream.Write(dataArray, 0, dataArray.Length);
dataStream.Close();
//读取返回消息
string res;
try
{
var response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
res = reader.ReadToEnd();
reader.Close();
}
catch (Exception ex)
{
var result = new ServerResult();
return "{\"error\":\"connectToServer\",\"error_description\":\"" + ex.Message + "\"}";//连接服务器失败
}
return res;
}
2:GET方式提交:
private static string HttpGetConnectToServer(string serverUrl, string postData)
{
//创建请求
var request = (HttpWebRequest)HttpWebRequest.Create(serverUrl + "?" + postData);
request.Method = "GET";
//设置上传服务的数据格式
request.ContentType = "application/x-www-form-urlencoded";
//请求的身份验证信息为默认
request.Credentials = CredentialCache.DefaultCredentials;
//请求超时时间
request.Timeout = 10000;
//读取返回消息
string res;
try
{
var response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
res = reader.ReadToEnd();
reader.Close();
}
catch (Exception ex)
{
var result = new ServerResult();
return "{\"error\":\"connectToServer\",\"error_description\":\"" + ex.Message + "\"}";
}
return res;
}
3:调用方法:
//服务地址
var serverUrl ="https://openapi.baidu.com/rest/2.0/devapi/v1/lightapp/query/isonline";
//上传的数据
var postData = string.Format("access_token={0}&offline_app_id={1}", token, appId);
上一篇:python基础
下一篇:Java自学-接口与继承 抽象类