几乎掌握了使用 Powershell Invoke-WebRequest 我现在开始尝试控制异常错误
在第一段代码中,我必须处理从 Web 服务返回的异常。您可以看到 400 代码与消息描述和详细消息一起返回。
Try {
$what = Invoke-WebRequest -Uri $GOODURL -Method Post -Body $RequestBody -ContentType $ContentType
}
catch [System.Net.WebException] {
$Request = $_.Exception
Write-host "Exception caught: $Request"
$crap = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim();
Write-Output $crap;
$crapMessage = ($_.Exception.Message).ToString().Trim();
Write-Output $crapMessage;
$crapdescription = ($_.ErrorDetails.Message).ToString().Trim();
Write-Output $crapdescription;
}
Run Code Online (Sandbox Code Playgroud)
输出返回。好的!
Exception caught: System.Net.WebException: The remote server returned an error: (400) Bad Request.
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
400
The remote server returned an error: (400) Bad Request.
Modus.queueFailed Could …Run Code Online (Sandbox Code Playgroud) 所以我有一些代码可以访问网站的 html,但只能在 Visualstudios.Framework for c# 中将此代码输入到 app.config 中。
<system.net> <defaultProxy useDefaultCredentials="true" /> </system.net>
Run Code Online (Sandbox Code Playgroud)
ps >< 之间的下一行
但我需要此代码在 .CORE 而不是 .FRAMEWORK 中工作,但它给出了此错误。
System.Net.WebException:“远程服务器返回错误:(407)需要代理身份验证。”
我尝试通过从解决方案资源管理器创建 app.config 来解决它,但它是否有效?互联网上的所有答案要么太复杂,要么显示我在 .FRAMEWORK 的 app.config 中放入了一点代码这不适用于 .Core
代码作为起点。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
{
readStream = new StreamReader(receiveStream);
Console.WriteLine("Sorry , somethings faulty");
}
else
{
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
readStream.ToString();
// Console.WriteLine(readStream);
}
string ImpureTexta = …Run Code Online (Sandbox Code Playgroud) 我使用MVC4 Web API创建了一个RESTful Web服务.如果出现问题,我会抛出WebException.
throw new WebException("Account not found");
Run Code Online (Sandbox Code Playgroud)
这是处理异常的客户端代码:
private void webClientPost_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
if (e.Error == null)
{
// Display result
textBoxResult.Text = e.Result;
}
else
{
// Display status code
if (e.Error is WebException)
{
StringBuilder displayMessage = new StringBuilder();
WebException we = (WebException)e.Error;
HttpWebResponse webResponse = (System.Net.HttpWebResponse)we.Response;
displayMessage.AppendLine(webResponse.StatusDescription);
// Gets the stream associated with the response.
Stream receiveStream = webResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level …Run Code Online (Sandbox Code Playgroud) .net httpwebresponse system.net.webexception asp.net-mvc-4 asp.net-web-api
我有一个桌面客户端,它通过 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(它是 …
我有以下代码进行调用,该调用又返回 xml:
private string Send(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
catch (WebException ex)
{
var _status = ex.Status.ToString();
if (ex.Status == WebExceptionStatus.ProtocolError)
{
_status = ((HttpWebResponse)ex.Response).StatusCode.ToString();
}
Trace.WriteLine(_status.ToString());
}
return "error";
}
Run Code Online (Sandbox Code Playgroud)
大多数时候(并非总是如此)我得到
System.Net.WebException: 服务器违反了协议。
System.Net.HttpWebRequest.GetResponse() 处的 Section=ResponseStatusLine
抛出异常。
我已将其直接添加到我的 App.config<configuration>部分中:
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true"/>
</settings>
</system.net>
Run Code Online (Sandbox Code Playgroud)
但我继续得到错误。
当我尝试获取不存在的页面或使用无效的HTTP方法时,HttpWebRequest.GetResponse()抛出System.Net.WebException一个Status属性为ProtocolError.在Message属性中,我可以在括号中看到HTTP状态代码.精细.但我没有看到整数StatusCode属性.我是否真的必须解析Message属性才能获得它?
.net httpwebrequest http-status-codes system.net.webexception