首页 > 编程语言 >C# Http 服务器get pos 请求 获取头信息 iOS 客户端联调

C# Http 服务器get pos 请求 获取头信息 iOS 客户端联调

时间:2023-02-14 11:56:22浏览次数:41  
标签:Http Log get Request listener context Debug 联调 string

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];
}

 

标签:Http,Log,get,Request,listener,context,Debug,联调,string
From: https://www.cnblogs.com/unity-android-ios/p/17119104.html

相关文章

  • 系统环境变量中 HTTP_PROXY 的误区
    前段时间在测试一个连麦demo,demo简要说可以在内网环境中运行时,输入频道号就可以模拟连麦但是在加入连麦时,一直返回错误-2EOF,询问得知,该错误的解释信息是“ServiceUna......
  • okhttp之复习
    一okhttp 1.简介:官方简介:OkHttp是一个默认高效的HTTP客户端1、HTTP2支持允许对同一主机的所有请求共享一个套接字。2、透明GZIP缩小了下载大小。3、连接池减少了请求......
  • c# - WebClient下载https协议文件报错 System.Net.WebException: 请求被中止: 未能创
    1.原因这是因为本地的 .net版本 低于4.6,但项目大多使用4.0或者4.5同时iis没有配置域名【本地测试机器一般都是没有域名的】2.解决方法1配置域名【服务器的才行,本......
  • 2023-02-14 Apps targeting Android 12 and higher are required to specify an expli
    新建android项目,选择basicactive一项,在跑模拟器的时候,报错。解决方案:找到AndroidManifest.xml文件,在<activity里面添加一行属性 android:exported="true"详情Gpt给出......
  • getClass和hashCode方法
    publicclassStudent{privateStringname;privateintage;publicStudent(Stringname,intage){}publicStringgetName(){returnna......
  • HTTPS双向认证
    双向认证,顾名思义,客户端和服务器端都需要验证对方的身份,在建立HTTPS连接的过程中,握手的流程比单向认证多了几步。单向认证的过程,客户端从服务器端下载服务器端公钥证书进行......
  • optee km4.0 VTS: PerInstance/SigningOperationsTest.RsaGetKeyCharacteristicsRequi
    异常日志:#./VtsHalKeymasterV4_0TargetTest--gtest_filter=PerInstance/SigningOperationsTest.RsaGetKeyCharacteristicsRequiresCorrectAppIdAppData/0_defaultNote......
  • pandas中的数据选取1(get/select_dtypes/isins/ample)
    数据筛选#1.头部数据与尾部数据#headdf.head(2)#获取前2行数据2.taildf.tail(2)#获取后2行数据#2.数据列的的获取df["name"]#df+列名称df.name#此种方法列名......
  • BurpSuite插件——新建UI界面且监听访问HTTP信息
    一、写在前面很久没更新了,一个是事情比较多、杂,而且这段时间有很多新知识和认知的冲击,不得不停下来沉淀一下。今天起正式开始一个新的模块——burp插件开发。 二、......
  • post和get的区别
    get和post是http请求的两种方法,它们的区别在于:1、GET请求通过URL(请求行)提交数据,在URL中可以看到所传参数。POST通过“请求体”传递数据,参数不会在url中显示。2、GET请求......