注: 本文使用了 .net库
System.Net.Http
以下是正文:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Xml;
using Azure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
//using Microsoft.Graph.Models;
//using Microsoft.Graph;
///using Microsoft.Graph.Models;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
HttpClient cs = new HttpClient();
HttpListener h = new HttpListener();
h.Prefixes.Add("http://127.0.0.1:11234/");//创建监听地址
h.Start();//启动监听
WebClient ap = new WebClient();
while (true)
{
HttpListenerContext co = h.GetContext();//等待访问
//h.GetContextAsync();
Console.WriteLine(co.Response.Headers + "," + co.User + "," + co.Request.RawUrl);
HttpListenerRequest re = co.Request;
HttpListenerResponse r = co.Response;
r.StatusCode = (int)HttpStatusCode.OK;//响应200码
r.ContentType = "application/json;charset=UTF-8";//返回mime类型
r.AppendHeader("Content-Type", "application/json;charset=UTF-8");
StreamWriter writer = new StreamWriter(r.OutputStream, Encoding.UTF8);//返回函数(文本类)
writer.Write("");//返回数据
writer.Close();
r.Close();
}
}
}
}
如果需要返回图片(png,jpg.....)或者压缩包(.7z,.zip,.rar.......)则需要以下更改:
while (true)
{
try
{
HttpListenerContext co = webstrat.h.GetContext();
HttpListenerRequest re = co.Request;
HttpListenerResponse r = co.Response;
r.StatusCode = (int)HttpStatusCode.OK;//标头状态码
r.ContentType = "image/png";//mime类型设定 图片类
Stream rf = r.OutputStream;//原始流
byte[] n = new byte[10240];
n = File.ReadAllBytes("C:\\Users\\Administrator\\Desktop\\1\\2");//以二进制方式读取
rf.Write(n, (int)r.ContentLength64, n.Length);//原始流,n为内容,(int)r.ContentLength64写入原始流多少后,n.Length写入长度
r.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
一些函数....:
h.Prefixes.First()//在HttpListener h 中获取列表第一个的打开端口
//HttpListenerContext co = h.GetContext();
co.Request.RawUrl//获取请求的url
//HttpListenerRequest re = co.Request;
re.HttpMethod//获取请求的方法(get,post)
住:mime类型决定浏览器识别内容类型。具体mime类型请上网搜索或根据实际使用情况自定。