我正在初始化一个HttpWebRequest,然后检索它的响应。偶尔,我会得到一个500 (或者至少是5##)错误,但是没有描述。我可以控制两个端点,并希望接收端获得更多信息。例如,我希望将异常消息从服务器传递到客户端。是否可以使用HttpWebRequest和HttpWebResponse?
代码:
try
{
HttpWebRequest webRequest = HttpWebRequest.Create(URL) as HttpWebRequest;
webRequest.Method = WebRequestMethods.Http.Get;
webRequest.Credentials = new NetworkCredential(Username, Password);
webRequest.ContentType = "application/x-www-form-urlencoded";
using(HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
{
if(response.StatusCode == HttpStatusCode.OK)
{
// Do stuff with response.GetResponseStream();
}
}
}
catch(Exception ex)
{
ShowError(ex);
// if the server returns a 500 error than the webRequest.GetResponse() method
// throws an exception and all I get is "The remote server returned an error: (500)."
}
这方面的任何帮助都将不胜感激。
发布于 2014-10-17 10:53:41
在尝试检查FTP站点上是否存在文件时,我遇到了这个问题。如果该文件不存在,则在尝试检查其时间戳时会出现错误。但我希望通过检查它的类型来确保错误不是其他原因。
WebException
上的Response
属性将是FtpWebResponse
类型,您可以在该属性上检查其StatusCode
属性,以查看您拥有的which FTP error。
下面是我最后使用的代码:
public static bool FileExists(string host, string username, string password, string filename)
{
// create FTP request
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + filename);
request.Credentials = new NetworkCredential(username, password);
// we want to get date stamp - to see if the file exists
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
var lastModified = response.LastModified;
// if we get the last modified date then the file exists
return true;
}
catch (WebException ex)
{
var ftpResponse = (FtpWebResponse)ex.Response;
// if the status code is 'file unavailable' then the file doesn't exist
// may be different depending upon FTP server software
if (ftpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
// some other error - like maybe internet is down
throw;
}
}
发布于 2016-09-14 17:14:33
HttpWebRequest myHttprequest = null;
HttpWebResponse myHttpresponse = null;
myHttpRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpRequest.Method = "POST";
myHttpRequest.ContentType = "application/x-www-form-urlencoded";
myHttpRequest.ContentLength = urinfo.Length;
StreamWriter writer = new StreamWriter(myHttprequest.GetRequestStream());
writer.Write(urinfo);
writer.Close();
myHttpresponse = (HttpWebResponse)myHttpRequest.GetResponse();
if (myHttpresponse.StatusCode == HttpStatusCode.OK)
{
//Perform necessary action based on response
}
myHttpresponse.Close();
https://stackoverflow.com/questions/7261986
复制相似问题