HTTP请求的服务端与客户端

 

====================客户端:=====================

HttpHelper

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace HttpClient
{
public class HttpHelper
{
public static string HttpGetAPI(string url)
{
try
{
System.Net.HttpWebRequest request;
// 创建一个HTTP请求
request = (System.Net.HttpWebRequest)WebRequest.Create(url);
request.Timeout = 6000;
request.Method = "get";
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = myreader.ReadToEnd();
myreader.Close();
return responseText;
}
catch (Exception ex)
{
return ex.Message;
}
}

/// <summary>
/// Json参数
/// </summary>
/// <param name="url"></param>
/// <param name="paraUrlJson"></param>
/// <returns></returns>
public static string HttpPostWebService(string url, string paraUrlJson)
{
try
{
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//Post请求方式
request.Method = "POST";
//内容类型
request.ContentType = "application/x-www-form-urlencoded";
//request.ContentType = "application/json";

request.Accept = "application/json-rpc";

byte[] payload;
//将Json字符串转化为字节

payload = System.Text.Encoding.UTF8.GetBytes(paraUrlJson);//编码为UTF-8
//payload = System.Text.Encoding.GetEncoding(ConfigurationManager.AppSettings["EncodingName"]).GetBytes(paraUrlJson);//编码为GB2312,可在App.config文件配置
//设置请求的ContentLength
request.ContentLength = payload.Length;
request.Timeout = 10000;
//发送请求,获得请求流
Stream writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象

//将请求参数写入流
writer.Write(payload, 0, payload.Length);
writer.Close();//关闭请求流

String strValue = "";//strValue为http响应所返回的字符流
//获得响应流
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
StreamReader reader = new StreamReader(s, Encoding.UTF8);
strValue = reader.ReadToEnd();
s.Close();
return strValue;//返回Json数据
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}

Client:

客户端Xaml代码

<Window x:Class="HttpClient.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:HttpClient"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="42" Margin="236,45,0,332" TextWrapping="Wrap" Text="http://localhost:8080/" VerticalAlignment="Center" VerticalContentAlignment="Center" Width="334" BorderThickness="1"/>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="354,114,0,0" VerticalAlignment="Top" Width="107" Height="37" Click="button_Click" RenderTransformOrigin="0.29,0.432"/>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="222,208,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Height="81" Width="397"/>
<Button x:Name="Clear" Content="Button" HorizontalAlignment="Left" Margin="354,332,0,0" VerticalAlignment="Top" Width="107" Height="37" Click="Clear_Click"/>
</Grid>
</Window>

客户端cs代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace HttpClient
{
public class HttpHelper
{
public static string HttpGetAPI(string url)
{
try
{
System.Net.HttpWebRequest request;
// 创建一个HTTP请求
request = (System.Net.HttpWebRequest)WebRequest.Create(url);
request.Timeout = 6000;
request.Method = "get";
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = myreader.ReadToEnd();
myreader.Close();
return responseText;
}
catch (Exception ex)
{
return "500";
}
}

/// <summary>
/// Json参数
/// </summary>
/// <param name="url"></param>
/// <param name="paraUrlJson"></param>
/// <returns></returns>
public static string HttpPostWebService(string url, string paraUrlJson)
{
try
{
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//Post请求方式
request.Method = "POST";
//内容类型
request.ContentType = "application/x-www-form-urlencoded";
//request.ContentType = "application/json";

request.Accept = "application/json-rpc";

byte[] payload;
//将Json字符串转化为字节

payload = System.Text.Encoding.UTF8.GetBytes(paraUrlJson);//编码为UTF-8
//payload = System.Text.Encoding.GetEncoding(ConfigurationManager.AppSettings["EncodingName"]).GetBytes(paraUrlJson);//编码为GB2312,可在App.config文件配置
//设置请求的ContentLength
request.ContentLength = payload.Length;
request.Timeout = 10000;
//发送请求,获得请求流
Stream writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象

//将请求参数写入流
writer.Write(payload, 0, payload.Length);
writer.Close();//关闭请求流

String strValue = "";//strValue为http响应所返回的字符流
//获得响应流
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
StreamReader reader = new StreamReader(s, Encoding.UTF8);
strValue = reader.ReadToEnd();
s.Close();
return strValue;//返回Json数据
}
catch (Exception ex)
{
return "500";
}
}
}
}

 ===============================客户端========================================

 ===============================Http服务端========================================

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HttpServer
{
class Program
{
static void Main(string[] args)
{
HttpListener httpListener = new HttpListener();

httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
httpListener.Prefixes.Add("http://localhost:8080/");
httpListener.Start();
new Thread(new ThreadStart(delegate
{
while (true)
{

HttpListenerContext httpListenerContext = httpListener.GetContext();
httpListenerContext.Response.StatusCode = 200;
using (StreamWriter writer = new StreamWriter(httpListenerContext.Response.OutputStream))
{
writer.WriteLine("<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>测试服务器</title></head><body>");
writer.WriteLine("<div style="height:20px;color:blue;text-align:center;"><p> hello</p></div>");
writer.WriteLine("<ul>");
writer.WriteLine("</ul>");
writer.WriteLine("</body></html>");

}

}
})).Start();
}
}
}

  ===============================Http服务端========================================

原文地址:https://www.cnblogs.com/zhaiganggang/p/14317599.html