简体   繁体   English

C# HttpWebRequest 异常 Cookies

[英]C# HttpWebRequest Exeption Cookies

Hi I'm trying to convert a python code to C#.嗨,我正在尝试将 python 代码转换为 C#。 My Problem is, that I have a problem to make a HttpWebRequest.我的问题是,我在制作 HttpWebRequest 时遇到问题。 I don't get the cookies for the POST Request.对于 POST 请求,我没有收到 cookies。

The Website response is 404. That is correct.网站响应是 404。这是正确的。 But I think, I need the cookies for the POST request.但我认为,我需要 cookies 来进行 POST 请求。

Is it correctly transleted?是否正确翻译? I have not done a HttpWebRequest yet.我还没有完成 HttpWebRequest。

C# Code: C# 代码:

public string email = "test@example.com"
public string password = "123456"
public string client_id = "111111111111"
public string login_url = "https://account.komoot.com/v1/signin"    


            var headers = new Dictionary<string, string> {

            {"Content-Type", "application/json"}};

            var payload = new Dictionary<string, string> {

            {"email", email},
            {"password", password},
            {"reason", "null"}};

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(login_url);
                request.CookieContainer = new CookieContainer();

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

            }
            catch (WebException ex)
            {
                var exeptionResponse = ex.Response;
                
                var cookies = exeptionResponse ["Cookies"];
                throw new WebException();
            }
           

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(login_url);
                request.CookieContainer = cookies;
                request.Method = "POST";
                request.ContentType = "application/json";
                using (var requestStream = request.GetRequestStream())
                using (var writer = new StreamWriter(requestStream))
                {
                    writer.Write(payload);
                }

                using (var responseStream = request.GetResponse().GetResponseStream())
                using (var reader = new StreamReader(responseStream))
                {
                    var result = reader.ReadToEnd();
                    Console.WriteLine(result);
                }
            }
            catch (Exception exe)
            {

                throw new Exception();
            }

Python Code: Python 代码:

import requests
import json

email = "test@example.com"
password = "123456"
client_id = "111111111111"
login_url = "https://account.komoot.com/v1/signin"
tour_url = f"https://www.komoot.de/user/{client_id}/tours"

s = requests.Session()

res = requests.get(login_url)
cookies = res.cookies.get_dict()

headers = {
    "Content-Type": "application/json"
}

payload = json.dumps({
    "email": email,
    "password": password,
    "reason": "null"
})

s.post(login_url,
       headers=headers,
       data=payload,
       cookies=cookies,
       )

url = "https://account.komoot.com/actions/transfer?type=signin"
s.get(url)

headers = {"onlyprops": "true"}

response = s.get(tour_url, headers=headers)
if response.status_code != 200:
    print("Something went wrong...")
    exit(1)

data = response.json()

tours = data["user"]["_embedded"]["tours"]["_embedded"]["items"]

for idx in range(len(tours)):
    print(f"({idx+1}) {tours[idx]['name']}")

tour_nr = int(input("Tour ID: "))
tour_nr -= 1
tour_url = tours[tour_nr]["_links"]["coordinates"]["href"]
response = s.get(tour_url, headers=headers)
tour_data = json.loads(response.text)

tour = tours[tour_nr]
tour['coordinates'] = tour_data

print("Title:", T.name())
print(f"Duration: {T.duration()}s")

Tanks for your help!坦克为您提供帮助!

Try it试试看

public async Task<string> HttpClientAsync(string json, string token)
        {
            try
            {
                var JsonData = new StringContent(json, Encoding.UTF8, "application/json");
                var handler = new HttpClientHandler();
                handler.ClientCertificateOptions = ClientCertificateOption.Manual;
                handler.ServerCertificateCustomValidationCallback =
                    (httpRequestMessage, cert, cetChain, policyErrors) =>
                    {
                        return true;
                    };
                using (var client = new HttpClient(handler))
                {
                  //  System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                    var result = await client.PostAsync(url, JsonData);
                    string resultContent = await result.Content.ReadAsStringAsync();
                    return resultContent;
                }
            }
            catch (Exception e)
            {
                return e.Message;
            }

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM