Photonic
Photonic

Reputation: 1421

Convert python http code to C#

I have this code here in python

response = requests.post(
    "https://gateway.watsonplatform.net/personality-insights/api/v2/profile",
    auth = ("username", "password"),
    headers = {"content-type": "text/plain"},
    data = "your text goes here"
)

jsonProfile = json.loads(response.text)

I am trying to convert it to C#, below is my code:

public void getRequest() {
        string url = "https://gateway.watsonplatform.net/personality-insights/api/v2/profile";
        using (var client = new WebClient())
        {
            var values = new NameValueCollection();
            values["username"] = username;
            values["password"] = password;
            values["content-type"] = "text/plain";
            values["data"] = getTestWords(@"D:\Userfiles\tchaiyaphan\Documents\API and Intelligence\storyTestWord.txt");

            var response = client.UploadValues(url, values);

            var responseString = Encoding.Default.GetString(response);
        }
    }

I don't know what to do with header section so i left that out. And when i ran the code it gave me an 401 error. I dont know what to do!

Upvotes: 0

Views: 950

Answers (2)

Photonic
Photonic

Reputation: 1421

Although ThiefMaster had manage to get me pass the authentication but it gave me a different error this time (415 Un-supported media type) so i decided to take a different approach and it works.

var request = (HttpWebRequest)WebRequest.Create("https://gateway.watsonplatform.net/personality-insights/api/v2/profile");

        var postData = getTestWords(@"D:\Userfiles\tchaiyaphan\Documents\API and Intelligence\storyTestWord.txt");

        var data = Encoding.ASCII.GetBytes(postData);

        request.Method = "POST";
        request.ContentType = "text/plain";
        request.ContentLength = data.Length;
        request.Credentials = new NetworkCredential(username, password);

        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)request.GetResponse();

        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318468

The problem is that your code is sending username and password as POST data instead of using the proper HTTP authorization header.

client.Credentials = new NetworkCredential(username, password);

Upvotes: 1

Related Questions