2017-12-18 110 views
0

我正在使用以下API將文件上傳到watson發現服務。即使我提供了一個有效的類型,我也會得到不支持的文件格式的響應。 API:discovery service api如何通過API將文檔上傳至watson發現服務。 ASP.net

public async Task<ActionResult> Index() 
    { 
     using (var httpClient = new HttpClient()) 
     { 

      //ADD BASIC AUTH 
      var authByteArray = Encoding.ASCII.GetBytes("{auth key}"); 
      var authString = Convert.ToBase64String(authByteArray); 
      httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authString); 

      var text = string.Empty; 
      var uri = "https://gateway.watsonplatform.net/discovery/api/v1/environments/{envid}/collections/{collectionid}/documents?version=2017-11-07"; 


      var content = new MultipartFormDataContent(); 
      var bytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Views/UploadDocument/civilwar-api1.html")); 
      var file = new StreamContent(new MemoryStream(bytes)); 
      content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/html"); 
      content.Add(new StreamContent(new MemoryStream(bytes)), "file"); 

      var response = await httpClient.PostAsync(uri, content); 
      var text1 = await response.Content.ReadAsStringAsync(); 

     } 

     return View(); 
    } 

API響應爲:{ "code" : 415, "error" : "Unsupported Media Type" }

回答

0

嘗試httpClient.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header

+0

儘管代碼只有答案才能解決問題,但有些解釋在理解解決方案以及將來如何解決類似問題方面有很長的路要走。 –

1

正如你可以看到沃森開發者雲,你可以使用.NET SDK

在此存儲庫中,您可以看到使用Watson的每項服務的examples

的方法來添加一個文件:

#region Documents 
     private void AddDocument() 
     { 
      Console.WriteLine(string.Format("\nCalling AddDocument()...")); 
      using (FileStream fs = File.OpenRead(_filepathToIngest)) 
      { 
       var result = _discovery.AddDocument(_createdEnvironmentId, _createdCollectionId, _createdConfigurationId, fs as Stream, _metadata); 

       if (result != null) 
       { 
        Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented)); 
        _createdDocumentId = result.DocumentId; 
       } 
       else 
       { 
        Console.WriteLine("result is null."); 
       } 
      } 
     } 
相關問題