我有一个桌面客户端,它通过 Http 与服务器端通信。当服务器在数据处理方面出现一些问题时,它会在 Http 响应正文中返回 JSON 中的错误描述,并带有正确的 Http 代码(主要是 HTTP-400)。
当我读到 HTTP-200 响应时,一切都很好,并且此代码有效:
using (var response = await httpRequest.GetResponseAsync(token))
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
return await reader.ReadToEndAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
但是当发生错误并且 WebException 被抛出并被捕获时,就会出现以下代码:
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
using (var response = (HttpWebResponse) ex.Response)
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream, Encoding.GetEncoding("utf-8")))
{
var json = reader.ReadToEnd();
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我已经对它做了一些处理,也许可以让它工作,但接下来发生了:
response.ContentLength有效(184)但stream.Length为0,之后我无法读取json(它是 …
我正在尝试构建一个应用程序,使用 httpwebrequests 从自定义网络服务器下载一个小二进制文件(20-25 KB)。
这是服务器端代码:
Stream UpdateRequest = context.Request.InputStream;
byte[] UpdateContent = new byte[context.Request.ContentLength64];
UpdateRequest.Read(UpdateContent, 0, UpdateContent.Length);
String remoteVersion = "";
for (int i = 0;i < UpdateContent.Length;i++) { //check if update is necessary
remoteVersion += (char)UpdateContent[i];
}
byte[] UpdateRequestResponse;
if (remoteVersion == remotePluginVersion) {
UpdateRequestResponse = new byte[1];
UpdateRequestResponse[0] = 0; //respond with a single byte set to 0 if no update is required
} else {
FileInfo info = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "remote logs", "PointAwarder.dll"));
UpdateRequestResponse = File.ReadAllBytes(Path.Combine(Directory.GetCurrentDirectory(), "remote …Run Code Online (Sandbox Code Playgroud) 所以我一直在用 C# 摆弄 Web 响应和请求,当我尝试运行该程序时遇到了问题。我的其中一行代码:
var response = await httpClient.SendAsync(request);
Run Code Online (Sandbox Code Playgroud)
方法制作中需要异步
private static void Main(string[] args)
Run Code Online (Sandbox Code Playgroud)
进入
private static async Task Main(string[] args)
Run Code Online (Sandbox Code Playgroud)
看起来没有错误,但是在构建时,我收到错误消息:
程序不包含适合入口点的静态“Main”方法。
这是我的代码
private static async Task Main(string[] args)
{
try
{
/*HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://billing.roblox.com/v1/gamecard/redeem");
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";
JsonExtensionDataAttribute data = new JsonExtensionDataAttribute();
data = '3335996838'*/
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://billing.roblox.com/v1/gamecard/redeem"))
{
request.Headers.TryAddWithoutValidation("Accept", "application/json");
request.Content = new StringContent("3335996838", Encoding.UTF8, "application/json"); …Run Code Online (Sandbox Code Playgroud) 您好我正在尝试制作一个将数据发布到joomla登录页面的应用程序,但我唯一得到的是cookie未启用.
Function GetPage(ByVal Url As String) As String
Dim CookieJar As New Net.CookieContainer
Dim enc As Encoding = Encoding.GetEncoding(1252)
Dim Data As Byte() = Nothing
Dim PostData As String = ""
If InStr(Url, "?") <> 0 Then
PostData = Url.Substring(InStr(Url, "?"))
Url = Replace(Url, PostData, "")
Url = Url.TrimEnd("?"c)
Data = enc.GetBytes(PostData)
End If
Dim req As System.Net.HttpWebRequest = CType(Net.WebRequest.Create(Url), Net.HttpWebRequest)
req.AllowAutoRedirect = False
req.ContentType = "application/x-www-form-urlencoded"
req.Method = "POST"
If Not Data Is Nothing Then
If Data.Length > 0 …Run Code Online (Sandbox Code Playgroud) 我有一个带有StreamReader的HttpWebRequest,它可以在不使用WebProxy的情况下工作得很好.当我使用WebProxy时,StreamReader会读取奇怪的字符而不是实际的html.这是代码.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://URL");
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10";
req.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
req.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
req.Headers.Add("Accept-Language", "en-US,en;q=0.8");
req.Method = "GET";
req.CookieContainer = new CookieContainer();
WebProxy proxy = new WebProxy("proxyIP:proxyPort");
proxy.Credentials = new NetworkCredential("proxyUser", "proxyPass");
req.Proxy = this.proxy;
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader reader = new StreamReader(res.GetResponseStream());
string html = reader.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)
不使用WebProxy,变量html保存URL中的预期html字符串.但是,使用a WebProxy,html保持这样的值:
"\b\0\0\0\0\0 \0 ]r s Y \0\tP \"] ki - …
我正在使用HttpWebRequest发送和接收Web请求.
在响应之后,通常是gzip内容编码.有些计算机会收到deflate编码.其他一些计算机将接收身份编码.
我把它设置为读取gzip和deflate编码但不确定如何读取身份编码.
string ReturnString = "";
HttpWebRequest HttpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
HttpWebRequest.ProtocolVersion = Version.Parse("1.1");
WebHeaderCollection WebHeaderCollection = HttpWebRequest.Headers;
HttpWebRequest.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
WebHeaderCollection.Add("Accept-Language: en-us");
WebHeaderCollection.Add("Accept-Encoding: gzip, deflate");
HttpWebRequest.KeepAlive = true;
HttpWebResponse HttpWebResponse = (HttpWebResponse)HttpWebRequest.GetResponse();
using (var mem = HttpWebResponse.GetResponseStream())
{
if (HttpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
{
using (var gzip = new GZipStream(mem, CompressionMode.Decompress))
{
using (var reader = new StreamReader(gzip))
{
ReturnString = reader.ReadToEnd();
}
}
}
else if (HttpWebResponse.ContentEncoding.ToLower().Contains("deflate"))
{
using (var gzip = new DeflateStream(mem, CompressionMode.Decompress)) …Run Code Online (Sandbox Code Playgroud) 我试图搜索之前关于这个问题的讨论,但我找不到一个,也许是因为我没有使用正确的关键字.
我正在编写一个小程序,将数据发布到网页上并获得响应.我发布数据的网站没有提供API.经过一些谷歌搜索后,我开始使用HttpWebRequest和HttpWebResponse.代码如下所示:
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://www.site.com/index.aspx");
CookieContainer cookie = new CookieContainer();
httpRequest.CookieContainer = cookie;
String sRequest = "SomeDataHere";
httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
httpRequest.Headers.Add("Accept-Encoding: gzip, deflate");
httpRequest.Headers.Add("Accept-Language: en-us,en;q=0.5");
httpRequest.Headers.Add("Cookie: SomecookieHere");
httpRequest.Host = "www.site.com";
httpRequest.Referer = "https://www.site.com/";
httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1";
httpRequest.ContentType = "application/x-www-form-urlencoded";
//httpRequest.Connection = "keep-alive";
httpRequest.ContentLength = sRequest.Length;
byte[] bytedata = Encoding.UTF8.GetBytes(sRequest);
httpRequest.ContentLength = bytedata.Length;
httpRequest.Method = "POST";
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Flush();
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
string sResponse;
using (Stream …Run Code Online (Sandbox Code Playgroud) c# asp.net httpwebrequest character-encoding httpwebresponse
我正在使用a WebRequest来阅读HTML网站.服务器似乎正在重定向我的请求.
我的代码类似于以下内容:
String URI = "http://www.foo.com/bar/index.html"
WebRequest req = WebRequest.Create(URI);
WebResponse resp = req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
String returnedContent = sr.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)
当我检查returnedContent它的内容包含来自重定向的内容,如"http://www.foo.com/FOO_BAR/index.html".我确信我请求的URL存在,因为它是收到的响应的一部分(作为IFrame).
有没有办法阻止WebResponse重定向并获取所请求的URL的内容?
UPDATE
设置req.AllowAutoRedirect = false导致302 Found状态代码,但不提供实际内容.
更多细节:我要求的网址是http://www.foo.com/bar/index.html我收到的内容http://www.foo.com/FOO_BAR/index.html
响应看起来类似于:
<body>
<div>
<iframe src="/foo/index.html"></iframe>
</div>
</body>
Run Code Online (Sandbox Code Playgroud) c# redirect httpwebrequest httpwebresponse http-status-code-302
我正在尝试编写一个重定向检查程序,我今天早上刚刚将这个解决方案捆绑在一起,所以它不是最有效的,但除了一件事,它做了我需要做的一切:
它只会在停止之前检查两个站点,没有错误发生,它只是在"request.GetResponse()上停止为HttpWebResponse;" 第三页的行.
我尝试过使用不同的网站并更改页面组合以进行检查,但它只检查了两个.
有任何想法吗?
string URLs = "/htmldom/default.asp/htmldom/dom_intro.asp/htmldom/dom_examples2.asp/xpath/default.asp";
string sURL = "http://www.w3schools.com/";
string[] u = Regex.Split(URLs, ".asp");
foreach (String site in u)
{
String superURL = sURL + site + ".asp";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(superURL);
request.Method = "HEAD";
request.AllowAutoRedirect = false;
var response = request.GetResponse() as HttpWebResponse;
String a = response.GetResponseHeader("Location");
Console.WriteLine("Site: " + site + "\nResponse Type: " + response.StatusCode + "\nRedirect page" + a + "\n\n");
}
Run Code Online (Sandbox Code Playgroud) 我正在写web下载器并遇到了这个奇怪的问题.示例代码:
int chunk;
var request = WebRequest.Create(uri) as HttpWebRequest;
using (WebResponse response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (Stream file = File.Create(filePath))
{
long byteReaded = 0;
long contentLength = response.ContentLength;
while (byteReaded < contentLength)
{
long bytesCountToRead = contentLength - byteReaded > chunk ? chunk : contentLength - byteReaded;
byte[] buffer = new byte[bytesCountToRead];
responseStream.Read(buffer, 0, buffer.Length);
file.Write(buffer, 0, buffer.Length);
byteReaded += bytesCountToRead;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题:当'chunk'变量== 1或2个字节时,它没问题.但是当这个尺寸更大时 - 图像会受到干扰!我已经发现它具有下载速度(响应读取速度),因为当我设置较大的尺寸chunk并插入Thread.Sleep(time) …