簡體   English   中英

C# HttpWebRequest 異常 Cookies

[英]C# HttpWebRequest Exeption Cookies

嗨,我正在嘗試將 python 代碼轉換為 C#。 我的問題是,我在制作 HttpWebRequest 時遇到問題。 對於 POST 請求,我沒有收到 cookies。

網站響應是 404。這是正確的。 但我認為,我需要 cookies 來進行 POST 請求。

是否正確翻譯? 我還沒有完成 HttpWebRequest。

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 代碼:

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")

坦克為您提供幫助!

試試看

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