public void TryConnectByHttpRequest()
{
HttpWebRequest httpReq = null;
try
{
if (!string.IsNullOrEmpty(this.servUrl))
{
string param = "test1=zh-CN&test2=request";
byte[] data = Encoding.ASCII.GetBytes(param);
httpReq = (HttpWebRequest)HttpWebRequest.Create(this.servUrl);
httpReq.Method = "POST";//不用Post用Get某些Http服务会报错:远程服务器返回错误: (411) 所需的长度。
httpReq.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
httpReq.ContentLength = data.Length;
//忽略缓存,完全使用服务器满足请求
httpReq.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
//响应延时为4S
httpReq.Timeout = 4000;
//这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据
httpReq.ServicePoint.Expect100Continue = false;
httpReq.ServicePoint.ConnectionLimit = 500;
using (Stream reqStream = httpReq.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
}
IAsyncResult result = httpReq.BeginGetResponse(new AsyncCallback(RespCallback), httpReq);
int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), httpReq, DefaultTimeout, true);
}
}
catch (WebException ex)
{
FrmMain.Instance.WriteClientLog("尝试连接Web服务出现异常:" + ex.Message);
}
}
public void TryConnectByHttpRequestGet()
{
HttpWebRequest httpReq = null;
try
{
if (!string.IsNullOrEmpty(this.servUrl))
{
httpReq = (HttpWebRequest)HttpWebRequest.Create(this.servUrl);
httpReq.Method = "GET";
httpReq.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
//忽略缓存,完全使用服务器满足请求
httpReq.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
//响应延时为4S
httpReq.Timeout = 4000;
IAsyncResult result = httpReq.BeginGetResponse(new AsyncCallback(RespCallback), httpReq);
int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), httpReq, DefaultTimeout, true);
}
}
catch (WebException ex)
{
FrmMain.Instance.WriteClientLog("尝试连接Web服务出现异常:" + ex.Message);
}
}
上面写的两个方法分别是用的Post 和Get请求!
客户公司提供了HTTP服务
我用Post方法正常连通 Get方法异常:远程服务器返回错误: (411) 所需的长度。
我自己用HttpListener写的Http服务
我用Post方法异常:操作超时 Get方法正常连通。
为啥会出现不同的情况啊?还有一般去请求HTTP到底是用Get还是Http啊?