webclient的简单实用

这是我在项目中调用别人写好的接口口是使用的
1、简单的url传参
List<ArticleModel> result = new List<ArticleModel>();
string str = string.Empty;
string url = "http://transfer.61read.com/Service/ResourceService/GetArticleResourceList/access_token/"
+ accessToken + "?";
if (resCategoryId != null)
{
url += "ResCategoryId=" + resCategoryId + "&";
}
if (pageindex != null)
{
url += "PageIndex=" + pageindex + "&";
}
if (pagesize != null)
{
url += "PageSize=" + pagesize + "&";
}
if (search != null)
{
url += "SearchTerm=" + search + "&";
}
if (isAsc != null)
{
url += "IsAsc=" + isAsc.ToString();
}
if (ResId != null)
{
url += "ResId=" + ResId + "&";
}
if (status != null)
{
url += "Status=" + status + "&";
}
url = url.TrimEnd(new char[] { '&', '?' });
Stream stream = new WebClient().OpenRead(url);
str = new StreamReader(stream).ReadToEnd();
ArticleResult resourceResult = JsonConvert.DeserializeObject<ArticleResult>(str);
List<ArticleModel> list = JsonConvert.DeserializeObject<List<ArticleModel>>
(resourceResult.GetArticleResourceListResult);
result = list.OrderBy(r => r.ResName).ToList();

return result;

还有就是规定使用特定的Method
public static void EditArticle(string accessToken, ArticleModel article, string resCateID)
{
string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(
new
{
entityJson = Newtonsoft.Json.JsonConvert.SerializeObject(
new
{
ResId = article.ResId,
ResName = article.ResName,
Status = article.Status,
Keyword = article.Keyword,
Thumbnail = article.Thumbnail,
CreateUserId = article.CreateUserId,
SubTitle = article.SubTitle,
Author = article.Author,
Content = article.ArticleContent,
ResCategoryId = resCateID
}
)
});

WebClient client = new WebClient();
byte[] sendData = Encoding.UTF8.GetBytes(jsonStr);
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("ContentLength", sendData.Length.ToString());
byte[] recData = client.UploadData
("http://transfer.61read.com/Service/ResourceService/UpdateArticle/access_token/" + accessToken, "Put", sendData);
client.Dispose();
string result = Encoding.GetEncoding("UTF-8").GetString(recData);
这个是调用方式是Put,传过去的事一个实体,使用client.UploadData的方法是必须传递数据
我在项目开发中遇到一个坑爹的问题就是使用Delete的调用方式只需要传递url传一个Id
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
Stream stream = client.OpenWrite(string.Format
("http://transfer.61read.com/Service/ResourceService/DeleteArticle/access_token/{0}/ResId/{1}", accessToken,
resCateID), "DELETE");
stream.Close();
client.Dispose();
需要尝试client里的不同方法,由于我的粗心大意,我把Delete写成了Deleted,搞的我调试了很久,还是别人给我看出来的;

转载于:https://www.cnblogs.com/xiaoweizi/p/3605360.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值