2010-08-11 70 views
1

我想使用c#(xml)向索引添加文档,但是我总是收到错误400(错误的请求)。任何想法我做错了什么?使用c#添加文档

代码:

private static string GetXml() 
    { 
     XDocument document = new XDocument(
      new XDeclaration("1.0", "UTF-8", "yes"), 
      new XElement("add", 
       new XElement("doc", 
        new XElement("field", 
         new XAttribute("name", "employeeId"), 
         new XText("05991")), 
        new XElement("field", 
         new XAttribute("name", "skills"), 
         new XText("Perl")) 
        ) 
       ) 
      ); 
     return document.ToString(SaveOptions.DisableFormatting); 
    } 

    private static void AddDocument() 
    { 
     string content = GetXml(); 
     HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://mysolrhost:8080/solr/update"); 
     request.Method = "POST"; 
     request.ContentType = "text/xml; charset=utf-8"; 
     byte[] byteArray = Encoding.UTF8.GetBytes(content); 
     request.ContentLength = byteArray.Length; 

     using (var requestStream = request.GetRequestStream()) 
     using (var sw = new StreamWriter(requestStream)) 
     { 
      sw.Write(content); 
     } 
     WebResponse response = request.GetResponse(); 
     Console.WriteLine(((HttpWebResponse) response).StatusDescription); 
    } 

    public static void Main(string[] args) 
    { 
     AddDocument(); 
    } 

编辑:问题解决(见下面的答案)。

非常感谢!

+0

可能想看看(例如)小提琴手中的http流量,看看导线上发生了什么 – 2010-08-11 08:05:25

回答

0

啊,傻了,我忘了在模式中添加字段,这就是为什么我得到了400.现在一切都好了。

非常感谢!

1

这是在黑暗中拍摄的,但在类似的情况下,我已经让服务器无法在文档开始时处理BOM(它应该,恕我直言,很好)。一个简单的方法来试试,看看这是问题是:

  • 变化byte[] byteArray = new UTF8Encoding(false).GetBytes(content);
  • 摆脱的StreamWriter的(你不需要它在现有的代码),只是requestStream.Write(byteArray, 0, byteArray.Length);
+0

谢谢,我已经删除了StreamWriter,但似乎问题是我:)总之谢谢。 – rrejc 2010-08-11 08:34:33