远程服务器出错:(406)不可接受

时间:2017-06-22 16:24:40

标签: c# httpwebrequest

我正在尝试将文档发送到要存储的API。

我的代码是:

model

它只是尝试以JSON格式发送Document并始终返回WebException。

您可以在此处查看文档中的规范:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://open.domain.com:9090/services/rest/index/my_index/document?login=john&key=bag6swgsalaidhjdh47678sdff");
request.Method = WebRequestMethods.Http.Put;
request.ContentType = "application/json";
request.Accept = "application/json";
string data = doc.getJSON();
request.ContentLength = data.Length;

StreamWriter postStream = new StreamWriter(request.GetRequestStream());
postStream.Write(doc.getJSON());
postStream.Close();

try
{
    var response = (HttpWebResponse)request.GetResponse();
} catch (Exception e)
{
    Console.WriteLine("Error: "+e.Message);
}

以下是如何进行身份验证:

curl -XPUT -H "Content-Type: application/json" \
    -d '[{"lang": "ENGLISH","fields": [{ "name": "id", "value": 1 }]}]' \
    http://localhost:8080/services/rest/index/my_index/document

始终收到相同的异常:错误406无法接受。

那么,出了什么问题?

修改

Json格式的数据(数据):

  

{ “田”:[{ “名称”: “TITULO”, “值”:“EL   TITULO “},{” 名 “:” descripcion “ ”值“:” 埃尔   TITULO “},{” 名 “:” 自由 “ ”值“:” 埃尔   TITULO “},{” 名 “:” friendly_url “ ”值“:” 埃尔   titulo“},{”name“:”ID“,”value“:”el titulo“},{”name“:”url“,”value“:”el   TITULO “},{” 名 “:” url_imagen “ ”值“:” 埃尔   TITULO “},{” 名称 “:” PLATAFORMA”, “值”: “努埃瓦”},{ “名称”: “隐藏”, “值”: “0”}]

来自文档

使用JSON插入文档

使用此API在索引中创建或更新文档。

要求:OpenSearchServer v1.5

调用参数

网址:/ services / rest / index / {index_name} / document

方法:PUT

HTTP标头:

Content-Type(必填):application / json Accept(可选的返回类型):application / json或application / xml

网址参数:

index_name(必填):索引的名称。

原始数据(PUT): 一系列文件。

1 个答案:

答案 0 :(得分:0)

根据文档,无需发送ContentLength标题

request.ContentLength = data.Length;; // <-- remove this line

以下是一个更全面的代码块:

string apiUri = @"http://localhost:8080/services/rest/index/my_index/document";

var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUri);
httpWebRequest.Method = "PUT";  
httpWebRequest.ContentType = "application/json";
//httpWebRequest.Accept = "application/json";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    var data = new List<object>()
    {
        new
        {
            Lang = "ENGLISH",
            Fields = new List<object>()
            {
                new { Name = "id", Value = 1 }
            }
        }
    };
    string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var response = Newtonsoft.Json.JsonConvert.DeserializeObject<YourObjectType>(streamReader.ReadToEnd());
    return response; // do something with the response...
}

这将发送相当于:

curl -XPUT -H "Content-Type: application/json" \
-d '[{"lang": "ENGLISH","fields": [{ "name": "id", "value": 1 }]}]' \
http://localhost:8080/services/rest/index/my_index/document