Христофоров Юрий
Задача: требуется из Windows .NET приложения отправить POST запрос на сервер и получить результат работы запрошенного методом POST скрипта. Предусмотреть ситуацию, при которой скрипт на сервере защищен Basic авторизацией.
Ниже приведен пример на C# для решения данной задачи.
C# код:
// необходимые библиотеки
using System;
using System.Web;
using System.Collections;
using System.Text;
using System.IO;
using System.Net;
using System.Data;
// ......
WebResponse result = null;
WebRequest req = null;
Stream newStream = null;
Stream ReceiveStream = null;
StreamReader sr = null;
try
{
// Url запрашиваемогометодом POST скрипта
req = WebRequest.Create("servername/script.cgi");
req.Method = "POST";
req.Timeout = 120000;
// эта строка необходима только при защите скрипта на сервере Basic авторизацией
//req.Credentials = new NetworkCredential("login", "password");
req.ContentType = "application/x-www-form-urlencoded";
byte[] SomeBytes = null;
// передаем список пар параметров / значений для запрашиваемого скрипта методом POST
// в случае нескольких параметров необходимо использовать символ & для разделения параметров
// в данном случае используется кодировка windows-1251 для Url кодирования спец. символов значения параметров
SomeBytes = Encoding.GetEncoding(1251).GetBytes("ParamName1=" + HttpUtility.UrlEncode("ParamValue1", Encoding.GetEncoding(1251)));
req.ContentLength = SomeBytes.Length;
newStream = req.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();
// считываемрезультатработы
result = req.GetResponse();
ReceiveStream = result.GetResponseStream();
Encoding encode = Encoding.GetEncoding(1251);
sr = new StreamReader( ReceiveStream, encode );
Char[] read = new Char[256];
int count = sr.Read( read, 0, 256 );
string strOut = "";
while (count > 0)
{
String str = new String(read, 0, count);
strOut += str;
count = sr.Read(read, 0, 256);
}
Console.WriteLine("Результат работы запрошенного методом POST скрипта: " + strOut);
}
catch (Exception ex)
{
Console.WriteLine("Ошибка: "+ex.Message);
}
finally
{
if (newStream != null)
newStream.Close();
if (ReceiveStream != null)
ReceiveStream.Close();
if (sr != null)
sr.Close();
if (result != null)
result.Close();
}
Другие работы по теме:
Информационные интернет ресурсы по маркетингу
Лабораторная работа №1. . Государственные ресурсы. Сайт www.gks. Содержит стат информацию федерального и регионального уровня. Сайт президента РФ www.president.kremlin. Найти две ссылки на сервер гос. ресурсов.
The Denver Post
Введение 1 История Список литературы The Denver Post Введение The Denver Post (русск. Дэнвэр пост) — популярная газета США. Подобно большинству американских газет, создана как региональное издание. Однако, концепция регионального СМИ не помешала ей стать одной из влиятельнейших газет стран. Тираж: 255 452 копий по будням[1] и воскресный выпуск 704 806 экземпляров[2].
The Washington Post
Введение 1 История 2 О газете The Washington Post Введение «Вашингто́н по́ст» (англ. The Washington Post) — американская газета. Издаётся в городе Вашингтоне. Крупнейшая газета столицы Соединённых Штатов Америки, также входит в число старейших.
Как написать AJAX-приложение
Это два года назад AJAX был в диковинку (да и самого слова AJAX тогда ещё не выдумали). Теперь веб-приложения, страницы которых обновлялись на лету, в порядке вещей. Даже наоборот: без AJAX трудно представить себе некоторые сервисы.
XMLHttpRequest (AJAX)
Объект XMLHttpRequest (AJAX): отправка и обработка ответов HTTP-запросов с помощью JavaScript. Методы и свойства объекта, общие для Internet Explorer 5, Mozilla, Netscape 7. Алгоритм выполнения, JavaScript-код. PHP-скрипт получения данных из базы.
Создание приложений на AJAX
Функции технологии Ajax разработки Web-приложений: выполнение HTTP-запросов в клиентской части и анализ ответа XML-сервера. Создание данных объекта XMLHttpRequest для разных браузеров. Обработка с помощью сервлета. Функциональность задач в Ajax.
Разработка почтового клиента для операционной системы Windows
Доступ пользователей сети к электронным сообщениям, хранящимся на сервере. Описание программы, аутентификация простая, APOP и AUTH-аутентификация. Реализация функций, руководство пользователя, алгоритмы функционирования программы, графический интерфейс.
Создание Web-приложений в среде Delphi
Время первопроходцев HTML в скором времени закончится и вовсе, и их место займут профессионалы-программисты. Именно программисты, ибо уже в большей степени от их умения создать удобный в использование сайт зависит его успех.
Понятия ИС
Система - совокупность элементов взаимодействующих друг с другом, образующих определённую целостность, единство. Система характеризуется понятиями:
Технология ISAPI
Интерфейс Internet Server Application Program Interface (ISAPI) предназначен для программирования приложения (API) информационных служб интернета (IIS). ISAPI состоит из классов поддержки и структур, участвующих в программной эксплуатации IIS. Веб-приложения, использующие ISAPI для взаимодействия с IIS, реализуют это взаимодействие на веб-сервере Windows наиболее эффективным образом.
Dr Anthony D Johnson Essay Research Paper
Dr. Anthony D. Johnson Dr. Johnson was born in Brooklyn,New York. His father was a bus driver for the area and his mom worked at the local post office. Since he had no role
The Post Office Essay Research Paper
“The Post Office” There has always been one place that has filled me with dread. Every time I walk into the post office I feel an overwhelming sense of disgust and threat. There are several reasons why the post office affects me in these ways. I feel so disgusted when I walk in the post office because often they do not have the materials I need.
Post Impressionism Essay Research Paper Post ImpressionismArt
Post Impressionism Essay, Research Paper Post Impressionism Art critics first used the term post-impressionistic in 1911 to loosely describe the work of a few artists whose paintings reflect Impressionistic principles, but were created after the movement had lost favour in the late seventeenth century (around 1885).
Stress Essay Research Paper The Posttraumatic stress
Stress Essay, Research Paper The Post-traumatic stress disorder is a mental illness that may develop in people after a horrible experience. This is a big reaction to extreme stress. There are many causes, symptoms, and treatments for the post-traumatic stress disorder.
Postal Accidents Essay Research Paper Like all
Postal Accidents Essay, Research Paper Like all car accidents, one involving a postal truck a government vehicle is not much different. Rarely does an accident like this occur. They don’t happen mainly because the postal
Watergate Essay Research Paper During President Nixon
Watergate Essay, Research Paper During President Nixon’s administration there was a history making scandal called Watergate. Watergate was based on a conspired break-in into the democratic headquarters in the Watergate building. Throughout this time Nixon’s term was a very rocky one. A person believed to have ties to the president or a high official that confirmed the Watergate story to Washington Post reporters Woodward and Bernstien.
Post Traumatic Stress Disorder Afflicting Vietnam Veterans
Essay, Research Paper Post Traumatic Stress Disorder afflicts a number of vietnam veterans who suffered extremely traumatic, and often consistent, experiences in the vietnam war. Many who do not understand the disorder at all view PTSD(post traumatic stress disorder) as an elaborate diagnosis for a vague set of symptoms that would otherwise be associated with other psycological problems.
Usps United States Postal Service Essay Research
Paper On July 26, 1775, members of the Second Continental Congress held a meeting in Philedelphia and they had all agreed that a Postmaster General should be appointed for the United States. That statement signaled the birth of the Post Office Department, which is now the second oldest department or agency of the United States.
How To Get CosheCom For A Month
Free Essay, Research Paper Vlad Shvorin FCAs 10/15/01 1. Use of Scientific Terms 2. Use of significant figures. 3. Content The purpose of this lab is to find the difference between pennies made before and after 1982. This lab includes seven steps, they re listed below:
Review Of Ceremony Essay Research Paper Review
Review Of Ceremony Essay, Research Paper Review of Ceremony Ceremony, written by Leslie Marmon Silko, traces the alienation and destruction of a young Native American who must first come to terms with his past before he can overcome his post-traumatic stress. Throughout this novel, there are many symbols and examples of how not only the main character, but his culture as a whole was ignored, rejected, and destroyed.
Bio Lab Report Essay Research Paper This
Bio Lab Report Essay, Research Paper This study was done to determine and compare the suvivorship curves of people who died prior to1945 and after 1945. Many medical advances have been made in this
Post War Europe Essay Research Paper The
Post War Europe Essay, Research Paper The Duality of Local and Regional Factors in the Rise of Dictators in Post-War Europe After World War I, a majority of Europe was left in utter shambles. The physical and economic structures of a once industrial area had been reduced rubble. The people of the nations cried out for help, but to little avail.
Great Gatsby Essay Research Paper
F. Scott Fitzgerald s The Great Gatsby is an excellent portrayal of the frenzied post-war society known as the Jazz Age. During a time of social and political corruption, society was living in excess, and modern values where sharply in decline. It was a time of severe disillusionment, and through the characterizations in the novel, the image of a devalued society can clearly be seen, especially through the lusts and desires of Gatsby himself.
Xxx Essay Research Paper POST PAPER and
Xxx Essay, Research Paper POST PAPER and get PasswordIf you submit a paper, it will be immediately posted to the site and searchable within seconds. This alsowill give you immediate access to the Free Search engine with over 1,000 papers. Since most of you arelazy, we already knew that most of you will try to get past this screen without submitting a paper.
Дневник по преддипломной практике
РОССИЙСКИЙ ГОСУДАРСТВЕННЫЙ СОЦИАЛЬНЫЙ УНИВЕРСИТЕТ Филиал РГСУ в г. Тольятти Специальность «Финансы и кредит» Форма обучения очная Курс 5 ДНЕВНИК по преддипломной практике
Анатомічна будова N TRIGEMINUS
V-та пара черепномозкових нервів – це трійничний нерв,який складається з трьох гілок: n.ophtalmicus, n.maxillaris, n.mandibularis. 1)R.meningeus