using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using UnityEngine;
public class TestServerHttp : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
ListenAsync();
} private HttpListener listener;
// Update is called once per frame
async void ListenAsync()
{
try
{
IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
string localIp = "";
foreach (var ip in ipEntry.AddressList)
{
Debug.Log("IP Address: " + ip.ToString());
localIp = ip.ToString();
}
listener = new HttpListener();
//string url1 = string.Format($"http://{localIp}:51111/MyApp/");
string url2 = string.Format($"http://{localIp}:51111/MyApp/aa/");
string url3 = string.Format($"http://{localIp}:51111/MyApp/bb/");
Debug.Log("IP url: " + url2);
listener.Prefixes.Add(url2);
listener.Prefixes.Add(url2);
listener.Prefixes.Add(url3);
//listener.Prefixes.Add("http://localhost}:51111/wangermazi/");
listener.Start();
while (true)
{
HttpListenerContext context = await listener.GetContextAsync();
Dictionary<string, object> res = new Dictionary<string, object>();
res["succ"] = true;
res["content"] = "hah";
var item = MiniJSON.Json.Serialize(res);
Debug.Log(item);
//string msg = "You asked for: " + context.Request.RawUrl + Time.realtimeSinceStartup;
var msg = item;
context.Response.ContentLength64 = Encoding.UTF8.GetByteCount(msg);
context.Response.StatusCode = (int)HttpStatusCode.OK;
Debug.Log(context.Request.Url + " " + context.Request.RemoteEndPoint.Address);
Debug.Log("HttpMethod" + context.Request.HttpMethod);
if (context.Request.HasEntityBody)
{
Stream SourceStream = context.Request.InputStream;
byte[] currentChunk = ReadLineAsBytes(SourceStream);
//获取数据中有空白符需要去掉,输出的就是post请求的参数字符串 如:username=linezero
var length = context.Request.Headers["Content-Length"];
//var temp = Encoding.Default.GetString(currentChunk,0,int.Parse(length));
var temp = ReadString(context);
//byte last = currentChunk[int.Parse(length) + 1];
//Debug.Log("---" + currentChunk.Length);
Debug.Log("---" + length);
//Debug.Log("---" + last);
Debug.Log("temp" + temp);
byte[] buffer = new byte[1];
Debug.Log("buffer" + buffer[0]);
}
Debug.Log("QueryString " + context.Request.QueryString);
Debug.Log("name " + context.Request.QueryString["name"]);
Debug.Log("City " + context.Request.Headers["City"]);
using (Stream s = context.Response.OutputStream)
{
using (StreamWriter writer = new StreamWriter(s))
{
await writer.WriteAsync(msg);
}
}
}
}
catch (Exception e)
{
Debug.Log("ListenAsync: " + e);
listener.Stop();
} //
} private void OnDestroy()
{
if (listener != null)
{
listener.Stop();
}
} static byte[] ReadLineAsBytes(Stream SourceStream)
{
var resultStream = new MemoryStream();
while (true)
{
int data = SourceStream.ReadByte();
if (data > 0)
{
resultStream.WriteByte((byte)data);
}
else
{
break;
}
}
resultStream.Position = 0;
byte[] dataBytes = new byte[resultStream.Length];
resultStream.Read(dataBytes, 0, dataBytes.Length);
return dataBytes;
} static string ReadString(HttpListenerContext context)
{
using (Stream inputStream = context.Request.InputStream)
using (StreamReader reader = new StreamReader(inputStream))
{
string json = reader.ReadToEnd();
return json;
}
}
}

  iOS 代码

-(void)httGetSync{
NSString *urlString = @"http://192.168.6.31:51111/MyApp/?name=wangwu";
//NSCharacterSet *customAllowedSet = NSCharacterSet(charactersInString:"`#%^{}\"[]|\\<> ").invertedSet;
//NSCharacterSet *customAllowedSet = [[NSCharacterSet characterSetWithCharactersInString:@"!$&'()*+-./:;=?@_~%#[]"] invertedSet];
NSCharacterSet *customAllowedSet = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *urlstr = [urlString stringByAddingPercentEncodingWithAllowedCharacters:customAllowedSet];
NSURL *url = [NSURL URLWithString:urlstr]; NSLog(@"%@",url); //NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
[req setHTTPMethod:@"GET"]; NSString *getString = @"";
NSData *getdata = [getString dataUsingEncoding:NSUTF8StringEncoding];
[req setValue:@"wangermazi" forHTTPHeaderField:@"City"]; NSLog(@"Curr thread %@",[NSThread currentThread]); NSURLSession *shareSession = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [shareSession dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(data && error == nil){
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); NSLog(@"Curr thread %@",[NSThread currentThread]);
}
}]; [dataTask resume];
} -(void)httpPostSync11{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://192.168.6.31:51111/MyApp/"]];
//[request setHTTPMethod:@"GET"];
[request setHTTPMethod:@"POST"];
NSString* postString = [NSString stringWithFormat:@"n=%@&c=%@", @"w" ,@"b"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//NSData *poData = [postString dataUsingEncoding:NSUTF8StringEncoding]
//[request setHTTPBody:poData];
NSURLSession *shareSession = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [shareSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(data && error == nil){
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
[dataTask resume];
}

C# Http 服务器get pos 请求 获取头信息 iOS 客户端联调的更多相关文章

  1. HTTP请求响应头信息

    HTTP请求响应头信息 请求:(request) 组成部分: 请求行 请求头 请求体 请求行:请求信息的第一行 格式:请求方式 访问的资源 协议/版本 例如:GET /day0801/1.html H ...

  2. wget/curl查看请求响应头信息

    wget / curl 是两个比较方便的测试http功能的命令行工具,大多数情况下,测试http功能主要是查看请求响应 头信息 ,而给这两个工具加上适当的命令行参数即可轻易做到,其实查man手册就能找 ...

  3. nodejs向远程服务器发送post请求----融云Web SDK/客户端获取token

    最近要用到一个叫融云的及时通讯的SDK,在获取token这个步骤的时候有点卡顿,以防以后碰到类似的问题,再此记录一下. 客户端通过融云 SDK 每次连接服务器时,都需要向服务器提供 Token,以便验 ...

  4. nginx log记录请求的头信息

    记录访问的log,为了在出现特殊情况时,方便检查出现问题的地方.log_format accesslog ‘$remote_addr – $remote_user [$time_local] “$re ...

  5. js获取设备公网ip + 服务器根据公网ip 获取IP信息

    1.前言 本来呢,想实现js定位功能,最少定位到城市,一开始,使用的是搜狐的api直接获取数据,可是,有时候搜狐不可靠,只能得到 公网ip,其他信息无用,就像这样 2.既然这样,还不如我自己请求自己的 ...

  6. nginx反向代理导致请求header头信息丢失

    背景:前端与后端调试接口,后端拿不到前段发过去的请求头信息,导致接口不通.(但是在本地是可以拿到的) 原因:nginx做了反向代理,没有请求时候加头信息的配置 报错如下: 解决方法: 方法一:NGIN ...

  7. Andriod的Http请求获取Cookie信息并同步保存,使第二次不用登录也可查看个人信息

    Android使用Http请求登录,则通过登录成功获取Cookie信息并同步,可以是下一次不用登录也可以查看到个人信息, 注:如果初始化加载登录,可通过缓存Cookie信息来验证是否要加载登录界面.C ...

  8. js获取http请求响应头信息

    var req = new XMLHttpRequest(); req.open('GET', document.location, false); req.send(null); var heade ...

  9. node获取头信息数据

    req.fresh req.stale var version = 100; app.get('/test',function(req,res){ res.set('etag',version); i ...

  10. Express之get,pos请求参数的获取

    Express的版本4.X Get query参数的获取 url假设:http://localhost:3000/users/zqzjs?name=zhaoqize&word=cool& ...

随机推荐

  1. 自动化处理日志脚本 shell

    自动处理脚本 保留7天的,带详细时间戳, #!/bin/sh #description split logs file1=/var/log/messages file2=/var/log/rabbit ...

  2. STP协议-进阶

    一 STP的选举规则1.在交换网络中选举一个根桥(Root Bridge)比较Bridge ID桥ID(优先级+MAC地址)越小越优 为了确保交换网络的稳定,建议提前规划STP组网,并将规划为根桥的交 ...

  3. llinux day02 基础操作 帮助 文件管理 马

    免密码登录(只是为了方便教学,免了图形界面的密码) 1,Linux免密自动以root身份登录图形化界面,修改etc/gdm/custom.conf 在deamon下面添加两行,注意区分大小写 [dae ...

  4. Java设计模式之策略模式(13)

    策略模式定义了一系列算法,每个算法封装起来,他们可以相互替换,且算法的变化不会影响到使用算法的客户.可以设计一个抽象类提供辅助. package WHP; public interface ICalc ...

  5. surfaceview+mediaplayer

    public class VideosurfaceView extends SurfaceView implements SurfaceHolder.Callback, MediaPlayer.OnP ...

  6. 【转载】win10怎么设置窗口护眼?

    转载地址:http://www.downza.cn/xy/122656.html win10设置窗口护眼模式的方法 2021-04-13 13:30:54来源:下载之家作者:down 小伙伴们你们知道 ...

  7. Kubernetes之Pod详解

    1.Pod生命周期 pod创建 1. API Server 在接收到创建pod的请求之后,会根据用户提交的参数值来创建一个运行时的pod对象. 2. 根据 API Server 请求的上下文的元数据来 ...

  8. nuxt项目中使用store

    首先初始化创建一个nuxt项目 nuxt项目创建以后,内部已自动集成store,所以无需再单独安装和引入 在根目录的store文件夹下新建文件,例如home.js //home.js export c ...

  9. vue remark重置 提交

    html: <el-table-column prop="remark" label="">                 <templat ...

  10. pytorch学习笔记(5)--神经网络

    (一)神经网络的骨架 nn.Module import torch from torch import nn class Tudui(nn.Module): def __init__(self): s ...