开发者

Strange HTTP authentication issue

I'm experiencing issues when trying to communicate with a web server (Apache 2.2.17) using Digest authentication, and sending data with the POST method: it always returns a 401 error. However, it works well when we don't post data, or when Fiddler is running (even when posting data)...Do you have an idea of what can cause the problem?

public void DoRequest(string v_strURL, XmlDocument v_objXMLDoc)
{

var credentialCache = new CredentialCache();

credentialCache.Add(new Uri("http://" + ServerIP + "/"), "Digest", new NetworkCredential("admin", "test", "realm"));

String RequestContent = "request=" + v_objXMLDoc.InnerXml.Replace(' ', '+');
Uri Url = new Uri(v_strURL);

HttpWebRequest objHttpWebRequest;
HttpWebResponse objHttpWebResponse = null;

Stream objRequestStream = null;

byte[] bytes = new byte[0];
bytes = System.Text.Encoding.UTF8.GetBytes(RequestContent);

objHttpWebRequest = (HttpWebRequest)WebRequest.Create(v_strURL);
objHttpWebRequest.UserAgent = "MySampleCode";
objHttpWebRequest.Credentials = credentialCache;
objHttpWebRequest.Method = "POST";
objHttpWebRequest.ContentLength = bytes.Length;
objHttpWebRequest.ContentType开发者_StackOverflow中文版 = "text/xml; encoding='utf-8'";
objHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

objRequestStream = objHttpWebRequest.GetRequestStream();
objRequestStream.Write(bytes, 0, bytes.Length);
objRequestStream.Close();

objHttpWebResponse = (HttpWebResponse)objHttpWebRequest.GetResponse();

}


Is there some reason you're setting the Content-Type header twice? That isn't likely to do what you want it to do. Also, why do you put the creds in the cache with the server IP rather than the hostname?

The HTTP/401 suggests that the server is challenging the client for credentials. The client is expected to respond by resubmitting the request with credentials attached. One key question is, in the failing case is the client trying to send the credentials and they're rejected, or not trying to send the credentials at all?

You probably should use Netmon or Wireshark for a lower-level look if Fiddler is "magically" fixing the problem for you.


Is the hostname in your HttpWebRequest.Create() call (i.e v_strUrl) the same as the hostname in the call to credentialCache.Add() ( i.e ServerIP ) ? If not, then this is going to fail always.

Instead of using CredentialCache, just add credentials directly to the HttpWebRequest object

request.Credentials = new NetworkCredential("user", "password", "realm");

and see if that works.


We finally have solved the problem:

objHttpWebRequest.ServicePoint.Expect100Continue = false;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜