我自己编写了一个非常简单的HTTP服务器,并使用C#Windows窗体来检索HTTP服务器的内容。我的C#程序总是说协议违规,CR必须跟着LF。我知道可以通过向C#Projects添加配置文件来解决此问题。但我想知道确切的原因。我的http服务器代码在下面。
/*
* This will handle connection for each client
* */
void *httpconnection_handler(void *socket_desc)
{
//Get the socket descriptor
int sock = *(int*)socket_desc;
int read_size;
char *message = "HTTP/1.1 200 OK\r\nContent-Type: text/xml; \r\ncharset=utf-8\r\n\r\n";
char *end = "\r\n";
char send_message[3000] = {0};
//Send some messages to the client
char * buffer = 0;
long length;
FILE * f = fopen ("/mnt/internal_sd/device-desc.xml", "r");
if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if (buffer)
{
fread (buffer, 1, length, f);
}
fclose (f);
}
strcat(send_message, message);
strcat(send_message, buffer);
strcat(send_message, end);
write(sock , send_message , length + strlen(message));
sleep(1);
shutdown(sock, SHUT_WR);
//Free the socket pointer
close(sock);
return 0;
}
我的C#代码在下面。
using (WebClient webClient = new WebClient())
{
webClient.Encoding = Encoding.UTF8;
contents = webClient.DownloadString(url);
}
确切的异常消息是
RequestFailed:服务器提交了协议违规。 Section = ResponseHeader Detail = CR必须后跟LF
答案 0 :(得分:3)
可能是因为\r\n
标题中有Content-Type
。 charset
应该是Content-Type
标题行的一部分。
char *message = "HTTP/1.1 200 OK\r\nContent-Type: text/xml;charset=utf-8\r\n\r\n";