C# Http访问帮助类
1 public class HttpHelper 2 { 3 /// <summary> 4 /// HttpWebRequest 通过Post 5 /// </summary> 6 /// <param name="url">URI</param> 7 /// <param name="postData">post数据</param> 8 /// <returns></returns> 9 public static string PostDataGetHtml(string url, string postData) 10 { 11 try 12 { 13 byte[] data = Encoding.UTF8.GetBytes(postData); 14 15 Uri uri = new Uri(url); 16 HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest; 17 if (req == null) 18 { 19 return "Network error:" + new ArgumentNullException("httpWebRequest").Message; 20 } 21 req.Method = "POST"; 22 req.KeepAlive = true; 23 req.ContentType = "application/x-www-form-urlencoded"; 24 req.ContentLength = data.Length; 25 req.AllowAutoRedirect = true; 26 27 Stream outStream = req.GetRequestStream(); 28 outStream.Write(data, 0, data.Length); 29 outStream.Close(); 30 31 var res = req.GetResponse() as HttpWebResponse; 32 if (res == null) 33 { 34 return "Network error:" + new ArgumentNullException("HttpWebResponse").Message; 35 } 36 Stream inStream = res.GetResponseStream(); 37 var sr = new StreamReader(inStream, Encoding.UTF8); 38 string htmlResult = sr.ReadToEnd(); 39 40 return htmlResult; 41 } 42 catch (Exception ex) 43 { 44 return "网络错误(Network error):" + ex.Message; 45 } 46 } 47 48 /// <summary> 49 /// HttpWebRequest 通过get 50 /// </summary> 51 /// <param name="url">URI</param> 52 /// <returns></returns> 53 public static string GetDataGetHtml(string url) 54 { 55 try 56 { 57 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); 58 59 httpWebRequest.ContentType = "application/x-www-form-urlencoded"; 60 httpWebRequest.Method = "GET"; 61 //对发送的数据不使用缓存 62 httpWebRequest.AllowWriteStreamBuffering = false; 63 httpWebRequest.Timeout = 300000; 64 httpWebRequest.ServicePoint.Expect100Continue = false; 65 66 HttpWebResponse webRespon = (HttpWebResponse)httpWebRequest.GetResponse(); 67 Stream webStream = webRespon.GetResponseStream(); 68 if (webStream == null) 69 { 70 return "网络错误(Network error):" + new ArgumentNullException("webStream"); 71 } 72 StreamReader streamReader = new StreamReader(webStream, Encoding.UTF8); 73 string responseContent = streamReader.ReadToEnd(); 74 75 webRespon.Close(); 76 streamReader.Close(); 77 78 return responseContent; 79 } 80 catch (Exception ex) 81 { 82 return "网络错误(Network error):" + ex.Message; 83 } 84 } 85 86 /// <summary> 87 /// HttpWebRequest 通过get 88 /// </summary> 89 /// <param name="url">URI</param> 90 /// <returns></returns> 91 public static bool GetDataGetHtml(string url, string filePath, ref string mg) 92 { 93 try 94 { 95 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); 96 97 httpWebRequest.ContentType = "application/x-www-form-urlencoded"; 98 httpWebRequest.Method = "GET"; 99 //对发送的数据不使用缓存 100 httpWebRequest.AllowWriteStreamBuffering = false; 101 httpWebRequest.Timeout = 300000; 102 httpWebRequest.ServicePoint.Expect100Continue = false; 103 104 HttpWebResponse webRespon = (HttpWebResponse)httpWebRequest.GetResponse(); 105 Stream webStream = webRespon.GetResponseStream(); 106 if (webStream == null) 107 { 108 return false; 109 } 110 StreamReader streamReader = new StreamReader(webStream, Encoding.UTF8); 111 string responseContent = streamReader.ReadToEnd(); 112 mg = responseContent; 113 webRespon.Close(); 114 streamReader.Close(); 115 if (responseContent.ToUpper().IndexOf("NULL") > -1) 116 { 117 return false; 118 } 119 else 120 { 121 FileStream fs = new FileStream(filePath, FileMode.Create); 122 var buff = Encoding.UTF8.GetBytes(responseContent); 123 fs.Write(buff, buff.Length, 0); 124 fs.Close(); 125 return true; 126 } 127 } 128 catch (Exception ex) 129 { 130 return false; 131 } 132 } 133 134 /// <summary> 135 /// 将本地文件上传到指定的服务器(HttpWebRequest方法) 136 /// </summary> 137 /// <param name="address">文件上传到的服务器</param> 138 /// <param name="fileNamePath">要上传的本地文件(全路径)</param> 139 /// <param name="saveName">文件上传后的名称</param> 140 /// <returns>成功返回1,失败返回0</returns> 141 public static int Upload_Request(string address, string fileNamePath, string saveName) 142 { 143 // 要上传的文件 144 try 145 { 146 if (!File.Exists(fileNamePath)) 147 { 148 return 0; 149 } 150 FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read); 151 return Upload_Request(address, fs, saveName); 152 } 153 catch (Exception ex) 154 { 155 return 0; 156 } 157 } 158 159 /// <summary> 160 /// 将本地文件流上传到指定的服务器(HttpWebRequest方法) 161 /// </summary> 162 /// <param name="address">文件上传到的服务器</param> 163 /// <param name="fileStream">要上传的本地文件流</param> 164 /// <param name="saveName">文件上传后的名称</param> 165 /// <returns>成功返回1,失败返回0</returns> 166 public static int Upload_Request(string address, Stream fileStream, string saveName) 167 { 168 int returnValue = 0; 169 fileStream.Position = 0; 170 var r = new BinaryReader(fileStream); 171 //时间戳 172 string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x"); 173 byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); 174 //请求头部信息 175 StringBuilder sb = new StringBuilder(); 176 sb.Append("--"); 177 sb.Append(strBoundary); 178 sb.Append("\r\n"); 179 sb.Append("Content-Disposition: form-data; name=\""); 180 sb.Append("file"); 181 sb.Append("\"; filename=\""); 182 sb.Append(saveName); 183 sb.Append("\""); 184 sb.Append("\r\n"); 185 sb.Append("Content-Type: "); 186 sb.Append("application/octet-stream"); 187 sb.Append("\r\n"); 188 sb.Append("\r\n"); 189 string strPostHeader = sb.ToString(); 190 byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader); 191 try 192 { 193 // 根据uri创建HttpWebRequest对象 194 HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address)); 195 httpReq.Method = "POST"; 196 //对发送的数据不使用缓存 197 httpReq.AllowWriteStreamBuffering = false; 198 //设置获得响应的超时时间(300秒) 199 httpReq.Timeout = 300000; 200 httpReq.ServicePoint.Expect100Continue = false; 201 httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary; 202 long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length; 203 long fileLength = fileStream.Length; 204 httpReq.ContentLength = length; 205 byte[] buffer = new byte[fileLength]; 206 Stream postStream = httpReq.GetRequestStream(); 207 //发送请求头部消息 208 postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); 209 int size = r.Read(buffer, 0, buffer.Length); 210 postStream.Write(buffer, 0, size); 211 //添加尾部的时间戳 212 postStream.Write(boundaryBytes, 0, boundaryBytes.Length); 213 postStream.Close(); 214 //获取服务器端的响应 215 HttpWebResponse webRespon = (HttpWebResponse)httpReq.GetResponse(); 216 if (webRespon.StatusCode == HttpStatusCode.OK) //如果服务器未响应,那么继续等待相应 217 { 218 Stream s = webRespon.GetResponseStream(); 219 StreamReader sr = new StreamReader(s); 220 //读取服务器端返回的消息 221 String sReturnString = sr.ReadLine(); 222 s.Close(); 223 sr.Close(); 224 fileStream.Close(); 225 if (sReturnString == "Success") 226 { 227 returnValue = 1; 228 } 229 else 230 { 231 returnValue = 0; 232 } 233 } 234 } 235 catch (Exception ex) 236 { 237 returnValue = 0; 238 } 239 return returnValue; 240 } 241 242 /// <summary> 243 /// 将本地文件上传到指定服务器上(HttpWebRequest方法),并传递相应参数 244 /// </summary> 245 /// <param name="url">文件上传到的服务器</param> 246 /// <param name="fileKeyName">类型(此处为文件--file)</param> 247 /// <param name="filePath">要上传的本地文件(全路径)</param> 248 /// <param name="filename">文件上传后的名称</param> 249 /// <param name="stringDict">参数集合</param> 250 /// <param name="timeOut">请求时效</param> 251 /// <returns></returns> 252 public static string HttpPostData(string url, string fileKeyName, string filePath, string filename, NameValueCollection stringDict, int timeOut = 900000) 253 { 254 string responseContent; 255 try 256 { 257 var memStream = new MemoryStream(); 258 var webRequest = (HttpWebRequest)WebRequest.Create(url); 259 // 边界符 260 var boundary = "---------------" + DateTime.Now.Ticks.ToString("x"); 261 // 边界符 262 var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); 263 var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); 264 // 最后的结束符 265 var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); 266 267 // 设置属性 268 webRequest.Method = "POST"; 269 webRequest.Timeout = timeOut; 270 webRequest.ContentType = "multipart/form-data; boundary=" + boundary; 271 272 // 写入文件 273 const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n"; 274 var header = string.Format(filePartHeader, fileKeyName, filename); 275 var headerbytes = Encoding.UTF8.GetBytes(header); 276 277 memStream.Write(beginBoundary, 0, beginBoundary.Length); 278 memStream.Write(headerbytes, 0, headerbytes.Length); 279 280 var buffer = new byte[1024]; 281 int bytesRead; // =0 282 283 while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) 284 { 285 memStream.Write(buffer, 0, bytesRead); 286 } 287 288 // 写入字符串的Key 289 var stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}\r\n"; 290 291 foreach (byte[] formitembytes in from string key in stringDict.Keys select string.Format(stringKeyHeader, key, stringDict[key]) into formitem select Encoding.UTF8.GetBytes(formitem)) 292 { 293 memStream.Write(formitembytes, 0, formitembytes.Length); 294 } 295 296 // 写入最后的结束边界符 297 memStream.Write(endBoundary, 0, endBoundary.Length); 298 299 webRequest.ContentLength = memStream.Length; 300 301 var requestStream = webRequest.GetRequestStream(); 302 303 memStream.Position = 0; 304 var tempBuffer = new byte[memStream.Length]; 305 memStream.Read(tempBuffer, 0, tempBuffer.Length); 306 memStream.Close(); 307 308 requestStream.Write(tempBuffer, 0, tempBuffer.Length); 309 requestStream.Close(); 310 311 var httpWebResponse = (HttpWebResponse)webRequest.GetResponse(); 312 313 using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"))) 314 { 315 responseContent = httpStreamReader.ReadToEnd(); 316 } 317 318 fileStream.Close(); 319 httpWebResponse.Close(); 320 webRequest.Abort(); 321 } 322 catch (Exception ex) 323 { 324 responseContent = ex.Message; 325 } 326 return responseContent; 327 } 328 329 /// <summary> 330 /// Http下载文件支持断点续传 331 /// </summary> 332 /// <param name="uri">下载地址</param> 333 /// <param name="filefullpath">存放完整路径(含文件名)</param> 334 /// <param name="size">每次多的大小</param> 335 /// <returns>下载操作是否成功</returns> 336 public static bool HttpDownLoadFiles(string uri, string filefullpath, int size = 1024) 337 { 338 try 339 { 340 string fileDirectory = System.IO.Path.GetDirectoryName(filefullpath); 341 if (!Directory.Exists(fileDirectory)) 342 { 343 Directory.CreateDirectory(fileDirectory); 344 } 345 string fileFullPath = filefullpath; 346 string fileTempFullPath = filefullpath + ".tmp"; 347 348 if (File.Exists(fileFullPath)) 349 { 350 return true; 351 } 352 else 353 { 354 if (File.Exists(fileTempFullPath)) 355 { 356 FileStream fs = new FileStream(fileTempFullPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); 357 358 byte[] buffer = new byte[512]; 359 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); 360 361 request.Timeout = 10000; 362 request.AddRange((int)fs.Length); 363 364 Stream ns = request.GetResponse().GetResponseStream(); 365 366 long contentLength = request.GetResponse().ContentLength; 367 368 int length = ns.Read(buffer, 0, buffer.Length); 369 370 while (length > 0) 371 { 372 fs.Write(buffer, 0, length); 373 374 buffer = new byte[512]; 375 376 length = ns.Read(buffer, 0, buffer.Length); 377 } 378 379 fs.Close(); 380 File.Move(fileTempFullPath, fileFullPath); 381 } 382 else 383 { 384 FileStream fs = new FileStream(fileTempFullPath, FileMode.Create); 385 386 byte[] buffer = new byte[512]; 387 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); 388 request.Timeout = 10000; 389 request.AddRange((int)fs.Length); 390 391 Stream ns = request.GetResponse().GetResponseStream(); 392 393 long contentLength = request.GetResponse().ContentLength; 394 395 int length = ns.Read(buffer, 0, buffer.Length); 396 397 while (length > 0) 398 { 399 fs.Write(buffer, 0, length); 400 401 buffer = new byte[512]; 402 403 length = ns.Read(buffer, 0, buffer.Length); 404 } 405 406 fs.Close(); 407 File.Move(fileTempFullPath, fileFullPath); 408 } 409 return true; 410 } 411 } 412 catch (Exception ex) 413 { 414 return false; 415 } 416 } 417 418 /// <summary> 419 /// Http下载文件 420 /// </summary> 421 /// <param name="uri">下载地址</param> 422 /// <param name="filefullpath">存放完整路径(含文件名)</param> 423 /// <param name="size">每次多的大小</param> 424 /// <returns>下载操作是否成功</returns> 425 public static bool DownLoadFiles(string uri, string filefullpath, int size = 1024) 426 { 427 try 428 { 429 if (File.Exists(filefullpath)) 430 { 431 try 432 { 433 File.Delete(filefullpath); 434 } 435 catch (Exception ex) 436 { 437 return false; 438 } 439 } 440 string fileDirectory = System.IO.Path.GetDirectoryName(filefullpath); 441 if (!Directory.Exists(fileDirectory)) 442 { 443 Directory.CreateDirectory(fileDirectory); 444 } 445 FileStream fs = new FileStream(filefullpath, FileMode.Create); 446 byte[] buffer = new byte[size]; 447 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); 448 request.Timeout = 10000; 449 request.AddRange((int)fs.Length); 450 451 Stream ns = request.GetResponse().GetResponseStream(); 452 453 long contentLength = request.GetResponse().ContentLength; 454 455 int length = ns.Read(buffer, 0, buffer.Length); 456 457 while (length > 0) 458 { 459 fs.Write(buffer, 0, length); 460 461 buffer = new byte[size]; 462 463 length = ns.Read(buffer, 0, buffer.Length); 464 } 465 fs.Close(); 466 return true; 467 } 468 catch (Exception ex) 469 { 470 return false; 471 } 472 } 473 }