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. Redis后端面试题

    目录 简要说一下什么是Redis? 为什么要⽤Redis(缓存)? 为什么要⽤Redis⽽不⽤map/guava做缓存? Redis与Memcached的区别 Redis的应⽤场景 redis为什么那 ...

  2. liunx设置QQ邮箱报警

    1.先安装一个软件包, 2.先登录电脑QQ邮箱->设置->账户->账户安全前两条选择开启,并生成授权码,授权码很重要很重要,千万不要泄露. 3.在liunx命令行输入  :vi /e ...

  3. laravel request lifecycle

    1,  index.php2, 生成service container3,  service provider register/booted4, dispatch routing5, middlew ...

  4. Android Studio: how to remove/update the “Created by” comment added to all new classes?

    By default Android Studio automatically adds a header comment to all new classes, e.g. /** * Created ...

  5. k8s_使用k8s部署wordpress博客系统(一)

    系统部署流程 使⽤kubernetes部署wordpress+MySQL, 并利⽤NFS去保存我们容器的源代码以及DB数据.搭建好nfs后任意node上的Pod访问db或者业务代码都会有相同的效果,数 ...

  6. logrotate配置记录

    对于一些比较频繁又没有太大意义的log,可以设定出更严格的切割策略 see https://blog.csdn.net/liuxiao723846/article/details/100120058 ...

  7. SSM项目

    1.环境搭建 1.1 结构目录 1.2 配置逆向工程 1.2.1 pom.xml <?xml version="1.0" encoding="UTF-8" ...

  8. P1062 [NOIP2006 普及组] 数列 题解

    目录 题目 思路 code 题目 P1062 [NOIP2006 普及组] 数列https://www.luogu.com.cn/problem/P1062 思路 先把 N 转换成 2 进制,再把这个 ...

  9. nginx的nginx.conf配置文件如何修改代理的路由

    方法 location /api/ { set $request_uri_new $request_uri; if ($request_uri ~ "^/api/(.*)$") { ...

  10. linux发展史及软件配置

    linux岗位需求 # 1.岗位需求 自动化运维,容器运维,DBA,IDC运维(不建议) ps:linux岗位会的越多给的越多 linux工作本质 linux简要发展史 # 1.发展 1991年,芬兰 ...