C# Http 服务器get pos 请求 获取头信息 iOS 客户端联调
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 客户端联调的更多相关文章
- HTTP请求响应头信息
HTTP请求响应头信息 请求:(request) 组成部分: 请求行 请求头 请求体 请求行:请求信息的第一行 格式:请求方式 访问的资源 协议/版本 例如:GET /day0801/1.html H ...
- wget/curl查看请求响应头信息
wget / curl 是两个比较方便的测试http功能的命令行工具,大多数情况下,测试http功能主要是查看请求响应 头信息 ,而给这两个工具加上适当的命令行参数即可轻易做到,其实查man手册就能找 ...
- nodejs向远程服务器发送post请求----融云Web SDK/客户端获取token
最近要用到一个叫融云的及时通讯的SDK,在获取token这个步骤的时候有点卡顿,以防以后碰到类似的问题,再此记录一下. 客户端通过融云 SDK 每次连接服务器时,都需要向服务器提供 Token,以便验 ...
- nginx log记录请求的头信息
记录访问的log,为了在出现特殊情况时,方便检查出现问题的地方.log_format accesslog ‘$remote_addr – $remote_user [$time_local] “$re ...
- js获取设备公网ip + 服务器根据公网ip 获取IP信息
1.前言 本来呢,想实现js定位功能,最少定位到城市,一开始,使用的是搜狐的api直接获取数据,可是,有时候搜狐不可靠,只能得到 公网ip,其他信息无用,就像这样 2.既然这样,还不如我自己请求自己的 ...
- nginx反向代理导致请求header头信息丢失
背景:前端与后端调试接口,后端拿不到前段发过去的请求头信息,导致接口不通.(但是在本地是可以拿到的) 原因:nginx做了反向代理,没有请求时候加头信息的配置 报错如下: 解决方法: 方法一:NGIN ...
- Andriod的Http请求获取Cookie信息并同步保存,使第二次不用登录也可查看个人信息
Android使用Http请求登录,则通过登录成功获取Cookie信息并同步,可以是下一次不用登录也可以查看到个人信息, 注:如果初始化加载登录,可通过缓存Cookie信息来验证是否要加载登录界面.C ...
- js获取http请求响应头信息
var req = new XMLHttpRequest(); req.open('GET', document.location, false); req.send(null); var heade ...
- node获取头信息数据
req.fresh req.stale var version = 100; app.get('/test',function(req,res){ res.set('etag',version); i ...
- Express之get,pos请求参数的获取
Express的版本4.X Get query参数的获取 url假设:http://localhost:3000/users/zqzjs?name=zhaoqize&word=cool& ...
随机推荐
- Java反射解析注解
package com.jeeplus.config; import javax.validation.constraints.Size; import java.lang.annotation.An ...
- vscode vue代码模板
{ "Print to console": { "prefix": "vue", "body": [ "< ...
- win11 改键盘映射
编辑注册表:按下win+r,输入regedit找到这个路径HKEY_LOCAL_MACHINE\ SYSTEM\ CurrentControlSet\ Control\ Keyboard Layout ...
- SQL 查找是否”存在”,别再用 COUNT 了,真的很费时间!
根据某一条件从数据库表中查询 『有』与『没有』,只有两种状态,那为什么在写SQL的时候,还要SELECT count(*) 呢?无论是刚入道的程序员新星,还是精湛沙场多年的程序员老手,都是一如既往的c ...
- vue super flow 多种形状
1 <template> 2 <v-container class="workflow-container" grid-list-xl fluid> 3 & ...
- DELL品牌电脑开机显示supportASsiSt丨pre-Boot SyStem Proforman?
这个问题,我百度了N个网站,得到的结果都是针对老版本BIOS的 https://wen.baidu.com/question/1647310335599401700.html https://zhua ...
- 在 RedHat 和 CentOS安装 Sphinx packages
一.Sphinx是什么 Sphinx是由俄罗斯人Andrew Aksyonoff开发的一个全文检索引擎.意图为其他应用提供高速.低空间占用.高结果 相关度的全文搜索功能.Sphinx可以非常容易的与S ...
- MySQL的MDL锁
MDL锁的概念和分类 1.MDL类型 锁名称 锁类型 说明 适用语句 MDL_INTENTION_EXCLUSIVE 共享锁 意向锁,锁住一个范围 任何语句都会获取MDL意向锁, 然后再获取更强级别的 ...
- 【SQL Server】列名首字母大写
使用UPPER 和 LOWWER函数组合首字母大写.例如: 1 SELECT user_id,(UPPER(LEFT(name,1) ) + RIGHT(name , LEN(name) -1) )A ...
- 计算机网络基础(1): 拓扑结构/ OSI模型/ TCP/IP模型
来自mooc <计算机网络基础及应用>南京理工大学. <计算机网络技术>宁波城市职业技术学院.来自网易云课堂<计算机网络工程基础>高骞. chapter1 导论 计 ...