欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用C#获取远程图片 Form用户名与密码Authorization认证的实现

程序员文章站 2023-12-18 18:32:40
c#获取远程图片,需要form用户名和密码的authorization认证复制代码 代码如下:using system;using system.collections.g...

c#获取远程图片,需要form用户名和密码的authorization认证

复制代码 代码如下:

using system;
using system.collections.generic;
using system.drawing;
using system.io;
using system.linq;
using system.net;
using system.text;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;

namespace web.app_code
{
    public partial class getfleximage : system.web.ui.page
    {
        public static readonly log4net.ilog log = log4net.logmanager.getlogger(system.reflection.methodbase.getcurrentmethod().declaringtype);

        protected void page_load(object sender, eventargs e)
        {
            if(request["img"]==null||string.isnullorempty(request["img"]))
            {
                return;
            }
            try
            {
                string url = (request["img"]).replace("%","%25");
                httpwebrequest wrequest;
                httpwebresponse response = null;
                uri uri = new uri(url);
                credentialcache cc = new credentialcache();
                cc.add(uri, "basic", new networkcredential("epapi", "密码"));
                wrequest = (httpwebrequest)httpwebrequest.create(uri);
                wrequest.credentials = cc;
                wrequest.preauthenticate = true;
                wrequest.method = "post";
                wrequest.allowwritestreambuffering = false;
                wrequest.sendchunked = false;
                wrequest.keepalive = true;
                wrequest.contentlength = 0;

                //wrequest.sendchunked = true;
                //wrequest.contentlength = 100000;
                wrequest.timeout = 30000;
                wrequest.headers.add("authorization", "basic " + convert.tobase64string(new asciiencoding().getbytes("epapi:epapiadmin")));
                try
                {
                    response = (httpwebresponse)wrequest.getresponse();
                }
                catch (webexception er)
                {
                    response = (httpwebresponse)er.response;
                }
                bitmap myimage = new bitmap(response.getresponsestream());
                memorystream ms = new memorystream();
                myimage.save(ms, system.drawing.imaging.imageformat.gif);
                response.clearcontent();
                response.contenttype = "image/gif";
                log.debug("图片加载:" + (request["img"]));
                response.binarywrite(ms.toarray());
            }
            catch(exception err) {
                log.debug("图片加载异常:" + server.htmldecode(request["img"]) + err.message);
            }
        }
    }
}

上一篇:

下一篇: