本文介绍了C#中:如何执行使用套接字HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让使用套接字 HTTP请求。我的代码如下:

I am trying to make a HTTP request using sockets. My code is as follows:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class test
{
    public static void Main(String[] args)
    {
        string hostName = "127.0.0.1";
        int hostPort = 9887;
        int response = 0;

        IPAddress host = IPAddress.Parse(hostName);
        IPEndPoint hostep = new IPEndPoint(host, hostPort);
        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        sock.Connect(hostep);

        string request_url = "http://127.0.0.1/register?id=application/vnd-fullphat.test&title=My%20Test%20App";
        response = sock.Send(Encoding.UTF8.GetBytes(request_url));
        response = sock.Send(Encoding.UTF8.GetBytes("\r\n"));

        bytes = sock.Receive(bytesReceived, bytesReceived.Length, 0);
        page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
        Console.WriteLine(page);
        sock.Close();
    }
}

现在当我执行上面的代码没有任何反应,而当我在浏览器中输入我的 request_url 我从咆哮说应用程序注册,我从浏览器得到的回应是通知

Now when I execute the above code nothing happens whereas when I enter my request_url in browser I get a notification from Snarl saying that Application Registered and the response I get from browser is

SNP/2.0/0/OK/556

我从我的代码得到的回应是 SNP / 3.0 / 107 / BadPacket

The response I get from my code is SNP/3.0/107/BadPacket.

那么,什么是错我的代码。

So, what is wrong with my code.

推荐答案

您必须包含内容长度和中端双新行头指示结束。

You must include content-length and double new line in the end to indicate end of header.

var request = "GET /register?id=application/vnd-fullphat.test&title=My%20Test%20App HTTP/1.1\r\n" +
    "Host: 127.0.0.1\r\n" +
    "Content-Length: 0\r\n" +
    "\r\n";



HTTP 1.1规范可以在这里找到:的

这篇关于C#中:如何执行使用套接字HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 16:31