Форум программистов, компьютерный форум, киберфорум
C# .NET
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.86/7: Рейтинг темы: голосов - 7, средняя оценка - 4.86
0 / 0 / 0
Регистрация: 14.05.2011
Сообщений: 5
1
.NET 4.x

Отправка Сокета методом POST

20.08.2011, 18:36. Показов 1301. Ответов 2
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;
 
namespace BFT
{
    public partial class Form1 : Form
    {
        public const int Web_PAGE_STATUS_OK = 200;
        public const int Web_ERROR_UNKNOWN_ERROR = 0;
        public const int Web_ERROR_HOST_NOT_FOUND = -1;
        public const int Web_ERROR_CANT_CONNECT = -2;
        public const int Web_ERROR_UNAVAILABLE = -3;
        public const int Web_ERROR_UNKNOWN_CODE = -4;
        int Port { get; set; }
        //string id, auth;
        public Form1()
        {
            InitializeComponent();
            Port = 80;
        }
 
        StringBuilder pageContent = null;
        public StringBuilder PageContent
        {
            get { return pageContent; }
        }
 
        public int GetPageStatus(Uri url)
        {
            IPAddress address = GetAddress(url.Host);
            if (address == null)
            {
                return Web_ERROR_HOST_NOT_FOUND;
            }
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            EndPoint endPoint = new IPEndPoint(address, Port);
 
            try
            {
                socket.Connect(endPoint);
            }
            catch (Exception)
            {
                return Web_ERROR_CANT_CONNECT;
            }
 
            string command = GetCommand(url);
            byte[] bytesSent = Encoding.ASCII.GetBytes(command.Substring(1, command.Length - 1) + "\r\n");
            socket.Send(bytesSent);
            byte[] buffer = new byte[1024];
            int readBytes;
            int result = Web_ERROR_UNAVAILABLE;
            pageContent = null;
            readBytes = socket.Receive(buffer);
            string resultStr = Encoding.UTF8.GetString(buffer, 0, readBytes);
            if (pageContent == null)
            {
                string statusStr = resultStr.Remove(0, resultStr.IndexOf(' ') + 1);
 
                try
                {
                    result = Convert.ToInt32(statusStr.Substring(0, 3));
                }
                catch (Exception)
                {
                    result = Web_ERROR_UNKNOWN_CODE;
                }
                pageContent = new StringBuilder();
            }
            pageContent.Append(resultStr);
            socket.Close();
            return result;
        }
 
        protected string GetCommand(Uri url)
        {
            string var = "method=getInfo&sig=96cec58f0faebef58003818bc98123df&user=143459332&key=be6565148877a40538af2b1dbe82cf63";
            byte[] io = Encoding.ASCII.GetBytes(var);
            string command = "POST " + url.PathAndQuery + " HTTP/1.0\r\n";
            command += "Host: " + url.Host + "\r\n";
            command += "Content-Length: " + io.Length + "\r\n";
            command += "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20100101 Firefox/6.0\r\n";
            command += "Content-Type: application/x-www-form-urlencoded\r\n";
            command += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
            return command;
        }
 
        public IPAddress GetAddress(string address)
        {
            IPAddress ipAddress = null;
            try
            {
                ipAddress = IPAddress.Parse(address);
            }
            catch (Exception)
            {
                IPHostEntry heserver;
                try
                {
                    heserver = Dns.GetHostEntry(address);
                    if (heserver.AddressList.Length == 0)
                    {
                        return null;
                    }
                    ipAddress = heserver.AddressList[0];
                }
                catch
                {
                    return null;
                }
            }
 
            return ipAddress;
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Uri url = new Uri("http://109.234.157.38/prison/universal.php?getInfo");
            GetPageStatus(url);
            MessageBox.Show(pageContent.ToString());
        }
    }
}
Но в ответ приходит не то что ожидалось( Хотя должна отображаться информация о играке
Пишет:
Код
<html>..<head><title>400 Bad Request</title></head>..<body bgcolor="white">..<center><h1>400 Bad Request</h1></center>..<hr><center>nginx/0.7.67</center>..</body>..</html>..
Подскажите что делать пожалуйста))
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
20.08.2011, 18:36
Ответы с готовыми решениями:

Отправка xml файла методом POST
В классе XmlWriter создаётся файл. using (var xmlwrite = XmlWriter.Create( ...

Отправка POST запроса
Прошу помощи, срочно !!! Нужно отправить POST запрос сайту, но POST запрос состоит в виде JSON....

Отправка POST запроса
Мне необходимо сделать ПО для авторегистрации на одном из сайтов. Делаю подобное первый раз. При...

Отправка POST запроса
Всем привет, нужно сделать код на C# чтобы он отправлял post запрос со следующим содержимым.

2
42 / 42 / 9
Регистрация: 27.06.2010
Сообщений: 91
20.08.2011, 18:52 2
Ваша ошибка:

Any client (e.g. your Web browser or our CheckUpDown robot) goes through the following cycle:

Obtain an IP address from the IP name of the site (the site URL without the leading 'http://'). This lookup (conversion of IP name to IP address) is provided by domain name servers (DNSs).
Open an IP socket connection to that IP address.
Write an HTTP data stream through that socket.
Receive an HTTP data stream back from the Web server in response. This data stream contains status codes whose values are determined by the HTTP protocol. Parse this data stream for status codes and other useful information.

This error occurs in the final step above when the client receives an HTTP status code it recognises as '400'.

Используйте для отправки запроса Webrequest и Webresponse.
0
0 / 0 / 0
Регистрация: 14.05.2011
Сообщений: 5
21.08.2011, 00:31  [ТС] 3
Мне нужно отправить POST запрос с помощью сокета, быть может еще кто-то другой сможет мне помочь?

Добавлено через 2 часа 39 минут
И на том спасибо. Я уже разобрался)
0
21.08.2011, 00:31
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
21.08.2011, 00:31
Помогаю со студенческими работами здесь

Отправка post-запроса С#
Доброго времени суток всем! Пытаюсь отправить пост-запрос на сайт. По идее в ответ должно придти...

Post FILE отправка файла
Image img = Image.FromFile(&quot;1.jpg&quot;); string post = MultipartContentFormatter.MakeString(&quot;from=&quot; +...

WebBrowser post отправка данных
Всем привет , я уже делал отправку данных средствами webbrowser но раньше она выглядела так ...

Отправка Post запроса (игра vk)
Подскажет кто где найти метод шифрования данных в игре Вконтакте дота 2: пудж а то пост запрос при...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru