0

我必须向第三方 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 .NET C# 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;

我已经阅读了所有我能找到的关于这个的问题,但我没有得到任何改进。提前致谢!

4

3 回答 3

2

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

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;

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

于 2009-09-17T15:51:20.650 回答
1

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

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
}

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

于 2009-09-17T15:54:54.263 回答
1
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;
    }
于 2015-02-05T13:44:09.543 回答