c# – 发送网络请求时出现问题

我使用以下方法使用HTTPWebRequest从Web服务中检索内容:

private void RetrieveSourceCode(Method method)
{
   try
      {
      String url = "http://123.123.123.123:8080/";

      CredentialCache myCache = new CredentialCache();
      myCache.Add(new Uri(url), "Basic", new NetworkCredential("user", "pwd"));

     HttpWebRequest request =(HttpWebRequest)WebRequest.Create("http://abc.abc.ch:8080/famixParser/projects/argouml/org.argouml.uml.ui.behavior.common_behavior.ActionAddSendActionSignal.doIt(java.util.Collection)");
     Console.WriteLine(request.RequestUri.ToString());
     request.Credentials = myCache;
     request.Accept = "text/plain";

     HttpWebResponse response;
     try
     {
         response = (HttpWebResponse)request.GetResponse();
     }
     catch (Exception e)
     {
        Console.WriteLine("exception when sending query: ");
        throw e;
     }
     Stream resStream = response.GetResponseStream();
     byte[] buf = new byte[8192];
     StringBuilder sb = new StringBuilder();
     string tempString = null;
     int count = 0;

     do
     {
                    // fill the buffer with data
                    count = resStream.Read(buf, 0, buf.Length);

                    // make sure we read some data
                    if (count != 0)
                    {
                        // translate from bytes to ASCII text
                        tempString = Encoding.ASCII.GetString(buf, 0, count);

                        // continue building the string
                        sb.Append(tempString);
                    }
                }
                while (count > 0); // any more data to read?

                String sourceCode = sb.ToString();
                method.setSourceCode(sourceCode);
                Console.WriteLine(sourceCode);
                request.Abort();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }


        }

现在我总是得到一个401 – 访问被拒绝的例外.我不知道为什么,因为如果我在我的webbrowser中使用相同的URL,它就可以了.可能是因为这些parantheses?

请注意:我在这里更改了服务器地址,因此它不能在这里工作,但出于保密原因我不得不这样做.

最佳答案 您缓存的网址和请求网址不同,我认为这意味着您的用户名和密码未在请求中传递.

String url = "http://123.123.123.123:8080/";

CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(url), "Basic", new NetworkCredential("user", "pwd"));

使用123.123

HttpWebRequest request =(HttpWebRequest)WebRequest.Create("http://abc.abc.ch:8080/famixParser/projects/argouml/org.argouml.uml.ui.behavior.common_behavior.ActionAddSendActionSignal.doIt(java.util.Collection)");

使用abc.ch

点赞