赞
踩
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.Collections;
namespace RestClient
{
public partial class ClientForm : Form
{
void MakeRequest()
{
ResponseTextBox.Text = "Please wait...";
var url = UrlTextBox.Text;
var method = VerbComboBox.Text;
var requestBody = RequestBodyTextBox.Text;
string reponseAsString = "";
string xmlString = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
XmlReader reader = new XmlTextReader(new StreamReader(response.GetResponseStream(), Encoding.Default));
XmlDocument doc = new XmlDocument();
doc.Load(reader);
string param = "deviceName"; //待查找的字段
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); //XML命名空间管理器
nsmgr.AddNamespace("urn", "urn:psialliance-org"); //添加命名空间
XmlNode sNode = doc.SelectSingleNode("//urn:"+param, nsmgr); //查找param节点
sNode.InnerText = "test"; //将节点的文本信息修改为test
//将XmlDocument转为string
MemoryStream stream = new MemoryStream();
XmlTextWriter mywriter = new XmlTextWriter(stream, null);
mywriter.Formatting = Formatting.None;
doc.Save(mywriter);
StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);
stream.Position = 0;
xmlString = sr.ReadToEnd();
//MessageBox.Show(xmlString);
reader.Close();
response.Close();
stream.Dispose();
mywriter.Close();
stream.Close();
request.Abort();
HttpWebRequest requestWrite = (HttpWebRequest)WebRequest.Create("http://192.168.1.100/PSIA/System/deviceInfo");
requestWrite.Method = "PUT";
SetBody(requestWrite, xmlString); //发送
response = (HttpWebResponse)requestWrite.GetResponse();
}
catch (Exception ex)
{
reponseAsString += "ERROR: " + ex.Message;
}
ResponseTextBox.Text = reponseAsString;
}
void SetBody(HttpWebRequest request1, string requestBody)
{
using (Stream requestStream = request1.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(requestBody);
MessageBox.Show(requestBody);
}
}
public ClientForm()
{
InitializeComponent();
}
void ClientForm_Load(object sender, EventArgs e)
{
VerbComboBox.SelectedIndex = 0;
UrlTextBox.Text = "http://192.168.1.100/PSIA/System/deviceInfo";
}
void ExecuteButton_Click(object sender, EventArgs e)
{
MakeRequest();
}
void UrlTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MakeRequest();
e.Handled = true;
}
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。