C# 带有自定义标头的 HTTP Post 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11141116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:40:35  来源:igfitidea点击:

HTTP Post request with custom header

c#http-headers

提问by Antonio

I want to make a HTTP Post request from C#. This request has a custom headers. When I try to start my program I received this exception:

我想从 C# 发出 HTTP Post 请求。此请求具有自定义标头。当我尝试启动我的程序时,我收到了这个异常:

Italian:

意大利语:

Questa intestazione deve essere modificata utilizzando la proprietà o il metodo appropriato. Nome parametro: name

Questa intestazione deve essere modificata utilizzando la proprietà o il medo appropriato。名称参数:名称

English:

英语:

This header must be modified using the appropriate property or method.

必须使用适当的属性或方法修改此标头。

On line: request.Headers.Add("Content-Type", "text/x-gwt-rpc; charset=utf-8");

在线的: request.Headers.Add("Content-Type", "text/x-gwt-rpc; charset=utf-8");

This is my code:

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections.Specialized;
using System.IO;
using System.Text.RegularExpressions;
using System.Dynamic;
using System.Collections;
using System.Collections.ObjectModel;
using System.Net.Security;
using System.Web;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            WebRequest request = WebRequest.Create("http://www.androidlost.com/androidlost/greet");
            request.Method = "POST";
            request.Headers.Add("Content-Type", "text/x-gwt-rpc; charset=utf-8");
            string postData = "Test";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
         }
    }
}

采纳答案by Andy

Use WebRequest.ContentType property. Some headers can be set using API properties only.

使用 WebRequest.ContentType 属性。某些标头只能使用 API 属性进行设置。

EDIT:

编辑:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.androidlost.com/androidlost/greet");
request.ContentType = "text/x-gwt-rpc; charset=utf-8";

回答by Xharze

According to the MSDN documentation, HttpWebRequest.Header Property.

根据 MSDN 文档,HttpWebRequest.Header Property

The Content-Type are modified using the ContentTypeproperty. This requires that you cast the WebRequestto HttpWebRequest

使用ContentType属性修改内容类型。这就需要你投的WebRequestHttpWebRequest

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.androidlost.com/androidlost/greet");