需求:在winfrom窗体中,可以根据服务器端图片的URL,将图片保存到本地后显示出来,ASP.NET中却没有权限将服务器上的图片保存到本地,看过别人用Cookie实现过,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _0922
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string url = string.Format("https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=regist&rand=sjrand&0.5173300584942714");
System.Net.WebRequest imgRequst = System.Net.WebRequest.Create(url);
//以流的方式保存图片
System.Drawing.Image downImage = System.Drawing.Image.FromStream(imgRequst.GetResponse().GetResponseStream());
string dertory = "C:\\test\\";
string fileName = string.Format("{0}.jpg", DateTime.Now.ToString("HHmmssffff"));
if (!System.IO.Directory.Exists(dertory))
{
System.IO.Directory.CreateDirectory(dertory);
}
downImage.Save(dertory + fileName,System.Drawing.Imaging.ImageFormat.Jpeg);
downImage.Dispose();
this.pictureBox1.Image = Image.FromFile(dertory+fileName);
}
}
}
模拟请求 下载图片吧
是的,
这是12306的问题,,你需要使用带证书的http请求。。。
目前遇到的问题貌似解决,供大家参考
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Security.Cryptography.X509Certificates; using System.Net.Security; namespace _0922w { public partial class WebForm1 : System.Web.UI.Page { static CookieContainer Cookies = new CookieContainer(); static HttpWebRequest myHttpWebRequest; protected void Page_Load(object sender, EventArgs e) { string oneUrl = "https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand"; myHttpWebRequest = (HttpWebRequest)WebRequest.Create(oneUrl);//请求的URL myHttpWebRequest.CookieContainer = Cookies;//*发送COOKIE //if (Session["tzcooket"] != null) // myHttpWebRequest.Headers.Set("Set-Cookie", Session["tzcooket"].ToString()); myHttpWebRequest.Method = "GET"; myHttpWebRequest.ContentType = "application/x-www-form-urlencoded"; //获取返回资源 HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse(); Stream responseStream = response.GetResponseStream(); System.Drawing.Image bitmapImage = System.Drawing.Bitmap.FromStream(responseStream) as System.Drawing.Image; bitmapImage.Save("D:\\documents\\visual studio 2015\\Projects\\0922\\0922w\\image\\1152165471.jpg", System.Drawing.Imaging.ImageFormat.Png); Image1.ImageUrl = "~/image/1152165471.jpg"; } } }