Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过HTTP/Post将JSON写入Solr_C#_Json_Rest_Solr - Fatal编程技术网

C# 通过HTTP/Post将JSON写入Solr

C# 通过HTTP/Post将JSON写入Solr,c#,json,rest,solr,C#,Json,Rest,Solr,我正在使用C#/Winforms/.NET4.0应用程序通过HTTP/POST使用JSON向Solr写信,以加快索引速度,并使用下面的代码。我给solr写了一个文档(基于这些),但不断收到“400个错误请求”。JSON看起来是干净的,没有问题 这似乎是一个语法问题,但在过去的几个小时里,我一直在努力解决这个问题,但毫无结果。有什么不对的想法吗?谢谢你的帮助 这是正在发布的URI字符串 "http://localhost:8080/solr/update/json -H 'Content-type

我正在使用C#/Winforms/.NET4.0应用程序通过HTTP/POST使用JSON向Solr写信,以加快索引速度,并使用下面的代码。我给solr写了一个文档(基于这些),但不断收到“400个错误请求”。JSON看起来是干净的,没有问题

这似乎是一个语法问题,但在过去的几个小时里,我一直在努力解决这个问题,但毫无结果。有什么不对的想法吗?谢谢你的帮助

这是正在发布的URI字符串

"http://localhost:8080/solr/update/json -H 'Content-type:application/json' -d ' [ {\"UUID\":\"d2a174e4-81d6-487f-b68d-392be5d3d47a\",\"Extension\":\".AVI\",\"VideoFileName\":\"Clip 1.avi\"} ' ]"

string uri = http://localhost:8080/solr/update/json;

public bool WriteJSONToSolr(string uri, string json)
        {
            WebRequest request = WebRequest.Create(uri + " -H 'Content-type:application/json' -d ' [ " + json + " ' ]" );
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(json);
            Stream stream = null;
            try
            { // send the Post
                request.ContentLength = bytes.Length;   //Count bytes to send
                stream = request.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);         //Send it
            }
            catch
            {
                return false;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            System.Net.WebResponse response = request.GetResponse();
            if (response == null) return false;

            return true;
        }

你忘了在
-H
前面加一个
空格
字符吗?

我今天遇到了同样的问题

试试这两件事

1) 请记住,您不能像这样发送json字符串

[{"A":"1","B":"0","C":"","D":"Washington"}]
相反,您可能需要调整json,使其更像

[{"A":"1","B":"0","D":"Washington"}]
Solr不喜欢空值

2) 第二个有帮助的技巧(通过“curl”向solr发送数据时):在向solr发送请求之前,尝试用两个双引号替换json字符串中的所有双引号


json=json.Replace(@“”,@“”)

代码不起作用的原因是您在.Net中使用了cURL语法

cURL是一个发送和接收HTTP请求的可执行文件,.Net是一个用于编程应用程序的框架

它们不一样

要使其与.Net一起工作,您首先应该发布到正确的uri,并且需要设置正确的ContentType属性,如下所示:

var uri = "http://localhost:8080/solr/update/json";
using (var r = WebRequest.Create(uri))
{
    r.ContentType = "application/json";
    r.Method = "POST";
    using (var rs = r.GetRequestStream())
        rs.Write // your data
    // get response
    // return response data
}
也就是说,为什么要给自己造成痛苦?只需使用一个已经有用于SolR操作的类型化API的SolR连接器

比如说


但是如果您不想使用它,那么至少要使用现代的HTTP API,如

,如果您要插入,那么您需要在json元素中使用add和doc。您还需要添加提交,以便更新索引。您还可以从uri中删除这些参数,因为您可以将它们添加到web请求对象中。最后,您应该在uri中有您的集合名称

string json = "{\"add\":{\"doc\":{"
  + "\"UUID\":\"d2a174e4-81d6-487f-b68d-392be5d3d47a\","
  + "\"Extension\":\".AVI\","
  + "\"VideoFileName\":\"Clip 1.avi\"}},";
  + "\"commit\":{}}";
string uri = "http://localhost:8080/solr/collection/update";

WebRequest request = WebRequest.Create(uri);
request.ContentType = "application/json";
request.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(json);
Stream stream = null;

try {
  request.ContentLength = bytes.Length;
  stream = request.GetRequestStream();
  stream.Write(bytes, 0, bytes.Length);
}
catch {
  return;
}
finally {
  if (stream != null) {
    stream.Close();
  }
}
System.Net.WebResponse response = request.GetResponse();
if (response == null) {
  return;
}
如果要向solr插入多个对象,则可以向json添加多个add对象或doc对象。例如

json = "{add:{doc:{keys:values}}, add:{doc:{keys:values}}, commit:{}}"


调试时,请查看solr的日志。它将提醒您solr端可能发生的任何问题。

首先,我认为您没有使用-d选项传递正确的json数据。。请查看代码中的以下格式化代码

" -H 'Content-type:application/json' -d ' [ " + json + " ' ]" 
假设您的json数据是
{“name”:“sam”}
,则上述格式化结果为

-H 'Content-type:application/json' -d ' [{"name":"sam"} ' ]
您正在传递一个json数据,其中缺少“]

除此之外,您在solr索引中更新文档的方法是错误的。看看下面的简单代码。 [顺便说一句:您可以在url中传递'commit'参数]

public async Task PostAsync()
{
    string json = "{\"add\": {\"doc\": {"
        + "\"id\":\"12345\","
        + "\"firstname\":\"Sam\","
        + "\"lastname\":\"Wills\","
        + "\"dob\":\"2016-12-14T00:00:00Z\""
        + "}}}";

    using (var client = new HttpClient())
    {
        string uri = "http://localhost:8983/solr/people/update/json?wt=json&commit=true";
        var jsonContent = new StringContent(json);
        await client.PostAsync(new Uri(uri), jsonContent);
    }
}
如果要更新特定字段而不是整个文档[部分更新],请使用以下代码段

public async Task PartialPostAsync()
{
    string json = "{\"add\": {\"doc\": {"
        + "\"id\":\"12345\","
        + "\"lastname\":{\"set\":\"George\"}"
        + "}}}";

    using (var client = new HttpClient())
    {
        string uri = "http://localhost:8983/solr/people/update/json?wt=json&commit=true";
        var jsonContent = new StringContent(json);
        await client.PostAsync(new Uri(uri), jsonContent);
    }
}

“id”字段是唯一的字段。

请在将json转换为流字节后尝试下面的代码

受保护的覆盖无效附加(LoggingEvent LoggingEvent)
{
字节[]体字节;
尝试
{
string body=BodyFormatter.CreateBody(loggingEvent,_参数);
bodyBytes=Encoding.UTF8.GetBytes(body);
}
捕获(例外e)
{
ErrorHandler.Error(“创建主体失败”,e);
返回;
}
HttpWebRequest request=BuildRequest();
request.BeginGetRequestStream(r=>
{
尝试
{
使用(Stream=request.EndGetRequestStream(r))
{
stream.BeginWrite(bodyBytes,0,bodyBytes.Length,c=>
{
尝试
{
stream.EndWrite(c);
request.BeginGetResponse(a=>
{
尝试
{
var response=request.EndGetResponse(a);
if(((HttpWebResponse)response.StatusCode!=HttpStatusCode.OK)
ErrorHandler.Error(“获取失败响应:”+((HttpWebResponse)response.StatusDescription);
response.Close();
}
捕获(例外e)
{
ErrorHandler.Error(“未能获得响应”,e);
}
},空);
}
捕获(例外e)
{
ErrorHandler.Error(“写入失败”,e);
}
},空);
}
}
捕获(例外e)
{
ErrorHandler.Error(“连接失败”,e);
}
},空);
}

不幸的是,所有这些迭代都在前后添加了空间。运气不好:-(.顺便说一句,Solr没有返回任何错误消息,或者只是一个400错误的请求,InnerException为null。ThxB但是,当您已经将json放在url中时,为什么还要发布json str?嗯……不确定这是否会造成不同。我正在尝试不同的组合。那么,为什么不尝试只执行
GetResponse()
。停止使用true/false作为控制流。您不是在处理流,而是在关闭流。不要像第一次返回false时那样捕获任何和所有异常。您也不是在处理WebRequest。
public async Task PartialPostAsync()
{
    string json = "{\"add\": {\"doc\": {"
        + "\"id\":\"12345\","
        + "\"lastname\":{\"set\":\"George\"}"
        + "}}}";

    using (var client = new HttpClient())
    {
        string uri = "http://localhost:8983/solr/people/update/json?wt=json&commit=true";
        var jsonContent = new StringContent(json);
        await client.PostAsync(new Uri(uri), jsonContent);
    }
}