Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net.Http;
- using System.Web;
- using System.Net;
- using System.IO;
- using System.Text;
- using System.Text.RegularExpressions;
- namespace WatsonWithWindowsForms
- {
- class WatsonQA
- {
- private string url;
- private string uid;
- private string pwd;
- public WatsonQA(string baseURL, string uid, string pwd)
- {
- this.url = baseURL + "api/v2/profile/";
- this.uid = uid;
- this.pwd = pwd;
- Console.WriteLine("url:" + this.url);
- Console.WriteLine("uid:" + this.uid);
- Console.WriteLine("pwd:" + this.pwd);
- }
- public string AskQuestion()
- {
- string answers = null;
- String line = "";
- using (StreamReader sr = new StreamReader("C:\\Appl_VB\\TestWatson\\Data\\Comments\\test.txt"))
- {
- line = sr.ReadToEnd();
- //Regex rgx = new Regex("[^a-zA-Z0-9 , .()!?$%]");
- //line = rgx.Replace(line, "");
- }
- string data = "";
- data += "{";
- data+= "\"contentItems\": [";
- data+= "{";
- data+= "\"id\": \"MyUser\",";
- data+= "\"userid\": \"author\",";
- data+= "\"sourceid\": \"reddit\",";
- data+= "\"contenttype\": \"text/plain\",";
- data+= "\"language\": \"en\",";
- data+= "\"content\":";
- data+= "\"" + line + "\",";
- data+= "}";
- data+= "]";
- data+= "}";
- string json = "{\"contentItems\": [{\"id\": \"xxx\",\"userid\": \"abc\", \"sourceid\": \"freetext\", \"contenttype\": \"text/plain\", \"language\": \"en\", \"content\": ";
- json += "\"";
- json += line;
- json += "\"";
- json += "}]}";
- var qaCall = (HttpWebRequest)WebRequest.Create(url);
- try
- {
- string auth = string.Format("{0}:{1}", this.uid, this.pwd);
- string auth64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
- string credentials = string.Format("{0} {1}", "Basic", auth64);
- qaCall.Headers[HttpRequestHeader.Authorization] = credentials;
- qaCall.Method = "POST";
- qaCall.Accept = "application/json";
- qaCall.ContentType = "application/json";
- var encoding = new UTF8Encoding();
- var payload = Encoding.GetEncoding("iso-8859-1").GetBytes(json);
- qaCall.ContentLength = payload.Length;
- using (var callStream = qaCall.GetRequestStream())
- {
- callStream.Write(payload, 0, payload.Length);
- }
- }
- catch (Exception e)
- {
- Console.Out.WriteLine("error:" + e.Message);
- Console.ReadKey();
- }
- try
- {
- WebResponse qaResponse = qaCall.GetResponse();
- Stream requestStream = qaResponse.GetResponseStream();
- StreamReader responseReader = new StreamReader(requestStream);
- answers = responseReader.ReadToEnd();
- responseReader.Close();
- }
- catch (System.Net.WebException e)
- {
- string toto = e.Response.ToString();
- Console.Out.WriteLine("errors:" + e.Message);
- Console.ReadKey();
- }
- catch (Exception e)
- {
- Console.Out.WriteLine("error:" + e.Message);
- Console.ReadKey();
- }
- return answers;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement