这是我用来在ASP中发出HTTP请求的一个小帮助函数.它在JScript中,但你应该至少得到这个想法,以及我们多年来不得不解决的一些令人讨厌的问题的一些指示.
<% /* Class: HttpRequest Object encapsulates the process of making an HTTP Request. Parameters: url - The gtarget url data - Any paramaters which are required by the request. method - Whether to send the request as POST or GET options - async (true|false): should we send this asyncronously (fire and forget) or should we wait and return the data we get back? Default is false Returns: Returns the result of the request in text format. */ var HttpRequest = function( url,data,method,options ) { options = options ? options : { "async" : false }; options[ "async" ] = options["async"] ? true : false; var text = ""; data = data ? data : ""; method = method ? String( method ).toupperCase() : "POST"; // Make the request var objXmlHttp = new ActiveXObject( "MSXML2.ServerXMLHTTP" ); objXmlHttp.setoption( 2,13056 ); // Ignore all SSL errors try { objXmlHttp.open( method,url,options[ "async" ] ); // Method,URL,Async? } catch (e) { text = "Open operation Failed: " + e.description; } objXmlHttp.setTimeouts( 30000,30000,30000 ); // Timeouts in ms for parts of communication: resolve,connect,send (per packet),receive (per packet) try { if ( method == "POST" ) { objXmlHttp.setRequestHeader( "Content-Type","application/x-www-form-urlencoded" ); } objXmlHttp.send( data ); if ( options[ "async" ] ) { return ""; } text = objXmlHttp.responseText; } catch(e) { text = "Send data Failed: " + e.description; } // Did we get a "200 OK" status? if ( objXmlHttp.status != 200 ) { // Non-OK HTTP response text = "Http Error: " + objXmlHttp.Status + " " + Server.HtmlEncode(objXmlHttp.StatusText) + "\nFailed to grab page data from: " + url; } objXmlHttp = null; // Be nice to the server return text ; } %>
如果将其保存在文件(称为httprequest.asp)中,则可以使用以下代码使用它:
<%@ Language="JScript" %> <!--#include file="httprequest.asp"--> <% var url = "http://www.google.co.uk/search"; var data = "q=the+stone+roses"; // Notice you will need to url encode your values,simply pass them in as a name/value string Response.Write( HttpRequest( url,"GET" ) ); %>
一句警告,如果有错误,它将返回给您错误消息,无法捕获它.它可以满足我们的需求,如果我们需要更多的保护,那么我们可以创建一个可以更好地处理错误的自定义函数.
希望有所帮助.
原文地址:https://www.jb51.cc/xml/293096.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。