views:

60

answers:

2

I am trying to add document to the index using c# (xml) but I am always getting error 400 (Bad request). Any ideas what I am doing wrong?

Code:

    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();
    }

Edit: the problem is solved (see the answer below).

Many thanks!

+1  A: 

It's a shot in the dark, but in similar situations I've had the server not be able to handle the BOM at the start of the document (which it should, IMHO, just fine). One simple way to try and see if this is the problem would be:

  • change to byte[] byteArray = new UTF8Encoding(false).GetBytes(content);
  • get rid of the StreamWriter (you don't need it in the existing code), just requestStream.Write(byteArray, 0, byteArray.Length);
James Manning
Thanks, I have removed StreamWriter, but it seems that the problem was me :) Thanks anyway.
rrejc
A: 

Ah, silly me, I forgot to add field in the schema and this is the reason why i got 400. Everything is ok now.

Many thanks!

rrejc