Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从Php到C的Https POST#_C#_Php_Post_Https_Code Migration - Fatal编程技术网

C# 从Php到C的Https POST#

C# 从Php到C的Https POST#,c#,php,post,https,code-migration,C#,Php,Post,Https,Code Migration,我必须向第三方https url发送帖子,以便处理和发送数据。我举的例子是: $signature= foo_string; $data_to_post = json_dictionary; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $base_url); curl_setopt($ch, CURLOPT_USERPWD, "$user:$password"); curl_setopt($ch, CURLOPT_HTTPAUTH, CURL

我必须向第三方https url发送帖子,以便处理和发送数据。我举的例子是:

$signature= foo_string;
$data_to_post = json_dictionary;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $base_url);
curl_setopt($ch, CURLOPT_USERPWD, "$user:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER,array("JSON-Signature: $signature"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_to_post);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
当我们使用ASP.NETC#2.0时,我必须对其进行移植,但我总是会遇到一个不合理的错误

以下是我正在做的:

HttpWebRequest q = (HttpWebRequest)WebRequest.Create(Host + ":" + Port);
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(new interhanse().AcceptAllCertifications);                

                q.Method = "POST";
                q.Headers.Add("JSON-Signature:" + GetSignature(data));
                q.ContentType = "application/json";

                q.UseDefaultCredentials = false;
                q.Credentials = new NetworkCredential(user,pwd, Host);

                byte[] buffer = UTF8Encoding.UTF8.GetBytes(data);

                q.ContentLength = data.Length;                

                Stream oStream = q.GetRequestStream();
                StreamWriter oWriter = new StreamWriter(oStream);
                oWriter.Write(buffer);
                oWriter.Close();


                HttpWebResponse reps = q.GetResponse() as HttpWebResponse;

我已经阅读了所有关于这方面的问题,但是我没有得到任何改进。提前谢谢

有一件事你做错了,那就是假设字节长度与字符长度相同。您应该使用buffer.Length作为内容长度。您还调用了
StreamWriter。使用字节数组编写
。您不应该这样做-您应该只使用流,因为您已经完成了编码:

byte[] buffer = Encoding.UTF8.GetBytes(data);

q.ContentLength = buffer.Length;
using (Stream stream = q.GetRequestStream())
{
    stream.Write(buffer, 0, buffer.Length);
}
现在,这并不能解决身份验证问题。您可能会发现,只需设置
PreAuthenticate
即可解决以下问题:

q.PreAuthenticate = true;

如果这不起作用,我建议您运行并查看通过Curl的请求与来自.NET的请求之间的差异。

好吧,您做错了一件事,那就是假设字节长度与字符长度相同。您应该使用buffer.Length作为内容长度。您还调用了
StreamWriter。使用字节数组编写
。您不应该这样做-您应该只使用流,因为您已经完成了编码:

byte[] buffer = Encoding.UTF8.GetBytes(data);

q.ContentLength = buffer.Length;
using (Stream stream = q.GetRequestStream())
{
    stream.Write(buffer, 0, buffer.Length);
}
现在,这并不能解决身份验证问题。您可能会发现,只需设置
PreAuthenticate
即可解决以下问题:

q.PreAuthenticate = true;

如果这不起作用,我建议您运行并查看通过Curl的请求与来自.NET的请求之间的差异。

我认为您不应该在身份验证中提供主机

q.Credentials = new NetworkCredential(user,pwd);
这大概是:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Host + ":" + Port);
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(new interhanse().AcceptAllCertifications);

request.Method = "POST";
request.Headers.Add("JSON-Signature:" + GetSignature(data));
request.ContentType = "application/json";

request.UseDefaultCredentials = false;
request.Credentials = new NetworkCredential(user, pwd);

byte[] buffer = UTF8Encoding.UTF8.GetBytes(data);

request.ContentLength = buffer.Length;
using (Stream oStream = request.GetRequestStream()) {
    oStream.Write(buffer, 0, buffer.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
    // load data from response here
}

另外,您应该避免在每个请求上分配服务点验证委托,这可能会越来越慢请求,因为验证会执行多次,而且这也是一种内存泄漏。

我认为您不应该在身份验证中提供主机

q.Credentials = new NetworkCredential(user,pwd);
curl_setopt($ch, CURLOPT_USERPWD, "$user:$password");
这大概是:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Host + ":" + Port);
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(new interhanse().AcceptAllCertifications);

request.Method = "POST";
request.Headers.Add("JSON-Signature:" + GetSignature(data));
request.ContentType = "application/json";

request.UseDefaultCredentials = false;
request.Credentials = new NetworkCredential(user, pwd);

byte[] buffer = UTF8Encoding.UTF8.GetBytes(data);

request.ContentLength = buffer.Length;
using (Stream oStream = request.GetRequestStream()) {
    oStream.Write(buffer, 0, buffer.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
    // load data from response here
}
此外,还应避免在每个请求上分配服务点验证委托,这可能会使请求速度越来越慢,因为验证要执行多次,而且这也是一种内存泄漏

curl_setopt($ch, CURLOPT_USERPWD, "$user:$password");
下面是如何在Asp.Net中添加CURLOPT_USERPWD的:

    private async Task<string> Execute(string url, string query, string user, string pasword)
    {
        HttpClient httpClient = new HttpClient();
        var baseUri = new Uri(url, UriKind.Absolute);  // e.g. http://somedomain.com/endpoint
        Uri request = new Uri(baseUri, query);    // with query e.g. http://somedomain.com/endpoint?arg1=xyz&arg2=abc

        // Add a new Request Message
        HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, request);

        // add headers -> CURLOPT_USERPWD equivalent
        var encodedStr = Convert.ToBase64String(Encoding.Default.GetBytes(string.Format("{0}:{1}", user, password)));
        var authorizationKey = "Basic" + " " + encodedStr;    // Note: Basic case sensitive
        requestMessage.Headers.Add("Authorization", authorizationKey);

        // if POST - do this instead
        // content
        //HttpContent content = new StringContent(jsonContent);     // string jsonContent i.e. JsonConvert.SerializeObject(YourObject);
        //requestMessage.Content = content;
        //requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        // execute
        HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage);
        var responseString = await responseMessage.Content.ReadAsStringAsync();    // reads it as string; 

        // if json and you need to convert to an object do this
        // var myresponse = JsonConvert.DeserializeObject<YourMappedObject>(responseString);

        return responseString;
    }
私有异步任务执行(字符串url、字符串查询、字符串用户、字符串密码)
{
HttpClient HttpClient=新HttpClient();
var baseUri=新Uri(url,UriKind.Absolute);//例如。http://somedomain.com/endpoint
Uri请求=新Uri(baseUri,query);//带有查询,例如。http://somedomain.com/endpoint?arg1=xyz&arg2=abc
//添加新的请求消息
HttpRequestMessage requestMessage=新的HttpRequestMessage(HttpMethod.Get,请求);
//添加标题->CURLOPT_USERPWD等效项
var encodedStr=Convert.ToBase64String(Encoding.Default.GetBytes(string.Format(“{0}:{1}”,用户,密码));
var authorizationKey=“Basic”+“”+encodedStr;//注意:Basic区分大小写
requestMessage.Headers.Add(“Authorization”,authorizationKey);
//如果是POST-请改为这样做
//内容
//HttpContent=new-StringContent(jsonContent);//string-jsonContent,即JsonConvert.SerializeObject(YourObject);
//requestMessage.Content=内容;
//requestMessage.Content.Headers.ContentType=新的MediaTypeHeaderValue(“应用程序/json”);
//执行
HttpResponseMessage responseMessage=等待httpClient.SendAsync(requestMessage);
var responseString=await responseMessage.Content.ReadAsStringAsync();//将其读取为字符串;
//如果json和您需要转换为对象,请执行此操作
//var myresponse=JsonConvert.DeserializeObject(responseString);
回报率;
}
下面是如何在Asp.Net中添加CURLOPT_USERPWD的:

    private async Task<string> Execute(string url, string query, string user, string pasword)
    {
        HttpClient httpClient = new HttpClient();
        var baseUri = new Uri(url, UriKind.Absolute);  // e.g. http://somedomain.com/endpoint
        Uri request = new Uri(baseUri, query);    // with query e.g. http://somedomain.com/endpoint?arg1=xyz&arg2=abc

        // Add a new Request Message
        HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, request);

        // add headers -> CURLOPT_USERPWD equivalent
        var encodedStr = Convert.ToBase64String(Encoding.Default.GetBytes(string.Format("{0}:{1}", user, password)));
        var authorizationKey = "Basic" + " " + encodedStr;    // Note: Basic case sensitive
        requestMessage.Headers.Add("Authorization", authorizationKey);

        // if POST - do this instead
        // content
        //HttpContent content = new StringContent(jsonContent);     // string jsonContent i.e. JsonConvert.SerializeObject(YourObject);
        //requestMessage.Content = content;
        //requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        // execute
        HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage);
        var responseString = await responseMessage.Content.ReadAsStringAsync();    // reads it as string; 

        // if json and you need to convert to an object do this
        // var myresponse = JsonConvert.DeserializeObject<YourMappedObject>(responseString);

        return responseString;
    }
私有异步任务执行(字符串url、字符串查询、字符串用户、字符串密码)
{
HttpClient HttpClient=新HttpClient();
var baseUri=新Uri(url,UriKind.Absolute);//例如。http://somedomain.com/endpoint
Uri请求=新Uri(baseUri,query);//带有查询,例如。http://somedomain.com/endpoint?arg1=xyz&arg2=abc
//添加新的请求消息
HttpRequestMessage requestMessage=新的HttpRequestMessage(HttpMethod.Get,请求);
//添加标题->CURLOPT_USERPWD等效项
var encodedStr=Convert.ToBase64String(Encoding.Default.GetBytes(string.Format(“{0}:{1}”,用户,密码));
var authorizationKey=“Basic”+“”+encodedStr;//注意:Basic区分大小写
requestMessage.Headers.Add(“Authorization”,authorizationKey);
//如果是POST-请改为这样做
//内容
//HttpContent=new-StringContent(jsonContent);//string-jsonContent,即JsonConvert.SerializeObject(YourObject);
//requestMessage.Content=内容;
//requestMessage.Content.Headers.ContentType=新的MediaTypeHeaderValue(“应用程序/json”);
//执行
HttpResponseMessage responseMessage=等待httpClient.SendAsync(requestMessage);
var responseString=await responseMessage.Content.ReadAsStringAsync();//将其读取为字符串;
//如果json和您需要转换为对象,请执行此操作
//var myresponse=JsonConvert.DeserializeObject(responseString);
回报率;
}

谢谢,错误现在改为:“连接已终止。未过期的接收错误。”但由于它们是自定义错误,我现在将请求支持:D非常感谢!谢谢,错误现在改为:“连接终止。未过期的接收错误。”但由于它们是自定义错误,我现在将请求支持:D非常感谢!没有更改错误,但由于它不在示例中,我将不再通过它。没有更改错误,但由于它不在示例中,我将不再通过它。