给定字符串中的URL:
http://www.example.com/test.xml
Run Code Online (Sandbox Code Playgroud)
将文件内容从服务器(由url指向)下载到C#中的字符串中,最简单/最简洁的方法是什么?
我现在这样做的方式是:
WebRequest request = WebRequest.Create("http://www.example.com/test.xml");
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)
这是很多代码,基本上可以是一行:
string responseFromServer = ????.GetStringFromUrl("http://www.example.com/test.xml");
Run Code Online (Sandbox Code Playgroud)
注意:我不担心异步调用 - 这不是生产代码.
我仍然是c#的新手,我正在尝试为这个页面创建一个应用程序,告诉我何时收到通知(回答,评论等等).但是现在我只是想简单地调用api来获取用户的数据.
我正在使用Visual Studio express 2012来构建C#应用程序,其中(现在)您输入了您的用户ID,因此应用程序将使用用户ID发出请求并显示此用户ID的统计信息.
这是我正在尝试发出请求的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Request library
using System.Net;
using System.IO;
namespace TestApplication
{
class Connect
{
public string id;
public string type;
protected string api = "https://api.stackexchange.com/2.2/";
protected string options = "?order=desc&sort=name&site=stackoverflow";
public string request()
{
string totalUrl = this.join(id);
return this.HttpGet(totalUrl);
}
protected string join(string s)
{
return api + type + "/" + s + options;
}
protected string get(string url)
{
try
{
string rt; …
Run Code Online (Sandbox Code Playgroud) 我的asp.net mvc Web应用程序中有以下WebClient:
using (WebClient wc = new WebClient()) // call the Third Party API to get the account id
{
string url = currentURL + "resources/" + ResourceID + "/accounts?AUTHTOKEN=" + pmtoken;
var json = await wc.DownloadStringTaskAsync(url);
}
Run Code Online (Sandbox Code Playgroud)
那么有人可以建议我如何将它从WebClient更改为HttpClient?
HttpClient是否使用与HttpWebRequest相同的ServicePoint连接限制?
谢谢
我有这个HttpWebRequest
:
var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");
request.ContentType = "application/json";
request.Method = "POST";
Run Code Online (Sandbox Code Playgroud)
但我需要在请求正文中添加一个有效负载,如下所示:
Jlpt = 2
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙告诉我如何向POST添加数据吗?
c# ×4
.net ×2
http ×1
httpclient ×1
httprequest ×1
networking ×1
webclient ×1
webrequest ×1
xamarin ×1