将python http代码转换为c#
本文关键字:转换 代码 python http | 更新日期: 2023-09-27 18:09:56
我在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)
我正试图将其转换为c#,下面是我的代码:
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);
}
}
我不知道如何处理标题部分,所以我把它省略了。当我运行代码时,它给了我一个401错误。我不知道该怎么办!
问题是您的代码将用户名和密码作为POST数据发送,而不是使用正确的HTTP授权头。
client.Credentials = new NetworkCredential(username, password);
虽然ThiefMaster已经设法让我通过身份验证,但这次它给了我一个不同的错误(415不支持的媒体类型),所以我决定采取不同的方法,它的工作。
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();